Angular asynchronous testing with Observable using karma

I am currently working on testing an asynchronous scenario. Here is a snippet of my component:

  ngOnInit(private service: MyService) {
    this.isLoading = true;
    this.service.getData().subscribe((data) => {
      this.data = data;
      this.isLoading = false;
    });
  }

In the code above, I set isLoading to true initially and then update it to false once the data is fetched successfully. This behavior is what I'm trying to test. I have attempted using tick(), whenStable() methods but so far have not been able to capture isLoading being true.

If anyone has any suggestions or solutions, I would greatly appreciate your help. Thank you.

Answer №1

it('should test the getData method of the service', done => {
  const testData = {};
  spyOn(component['service'], 'getData').and.returnValue(of(testData));
  component['service'].getData().pipe(delay(500)).subscribe(data => {
    expect(component.data).toBe(testData);
    expect(component.isLoading).toBeFalsy();
    done();
  });
  
  expect(component.isLoading).toBeTruthy();
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In Angular, there is an issue where the @ViewChild decorator does not reflect changes when the value of the child component is updated within the

Does anyone know why the console.log("My status :", status); is not displaying after the child property has changed? Here is my child component code: @Output() public isLoggedIn: Subject<boolean> = new Subject(); constructor( private auth ...

Having trouble integrating CKEditor into a React Typescript project

Error: 'CKEditor' is declared but its value is never read.ts(6133) A declaration file for module '@ckeditor/ckeditor5-react' could not be found. The path '/ProjectNameUnknown/node_modules/@ckeditor/ckeditor5-react/dist/ckeditor.js& ...

Can TypeScript support passing named rest arguments within the type declaration?

Using Tuple types in TypeScript enables us to create typesafe rest arguments: type Params = [string,number,string] const fn = (...args: Params) => null // Type is (args_0: string, args_1: number, args_2: string) => null Is there a method to assign ...

How to detect a change in the value of a formControl during each focusout event in Angular 6?

Within a child component, I have an input variable called @Input which measures in Inches. My form consists of 2 input text controls - 1. Foot 2. Inches I convert the @Input to feet and inches accordingly. The requirement is that only if the values are cha ...

Implementing ngClass change on click within an Angular component using Jasmine: A comprehensive guide

It seems like the click event is not triggering and the ngClass is not changing to active on the button I am attempting to click. -- HTML: <div class='btn-group' role='group' aria-label=""> <button type='button&apos ...

Manage scss styles consistently across Angular projects with this Angular library designed to

In an effort to streamline my development process, I am looking to consolidate my commonly used styles that are defined in my Angular library. My goal is to easily leverage mixins, functions, variables, and more from my library in future projects. Previou ...

Creating unit tests for a state that includes PreparedQueryOptions within Jasmine framework

Currently, I am in the process of writing a Jasmine test case for the state within Angular JS. The resolve section of my state looks something along these lines: resolve: { myResult: function () { var dfd = $q.defer(); ...

Retrieve every item in a JSON file based on a specific key and combine them into a fresh array

I have a JSON file containing contact information which I am retrieving using a service and the following function. My goal is to create a new array called 'contactList' that combines first names and last names from the contacts, adding an &apos ...

Assessing functionality in Angular8 by testing a function that accesses an array from a service

I have a function that I want to test along with the current test setup: canShowIt() { let showit = false; const profils = this.requestsService.userProfil; showit = profils.some((profil) => profil.id === this.profileDetail.id); return showit; ...

Conceal the Button when the TextBox does not contain valid input

I'm trying to create a textbox with an email pattern that hides a span (click) if the pattern is invalid. I have the following code snippet in place, but it doesn't seem to work as expected: <input type="text" placeholder="Signup for Mailin ...

What is the correct method for service injection in Angular 8?

I have encountered an issue while trying to inject a service into my main "App" component. The error message is shown in the screenshot below: constructor(private newsApi: NewsApiService) {} Upon importing the service using the code above, I received the ...

The Output() function seems to be failing to emit the event

My architecture setup is as follows: UiControlsModule |- Component 1 |- Component 2 The first module is imported and exported in SharedModule. CasesModule |- CaseListComponent |- // other components here SharedModule is also imported into CasesModule. ...

Implement Angular's Observable Subscription to fetch data from an API endpoint

Forgive me if I'm not using the correct terminology for Subjects and Observables. I am currently trying to subscribe to newImages in order to get a list of images. In my console, the response is as follows: [] [3] [7] [9] Each number represents ...

Utilize Pipe for every instance of a variable in the Controller

In my controller, I have multiple requests (POST, GET etc.) where the path includes an id parameter that needs to be a number string. I want to validate this parameter once and have it apply to all instances. Here is the current code snippet: @Get(&apo ...

Typescript: The type 'T' fails to meet the requirement of being an 'object'

Ever since I installed a package along with its @types package, I've been encountering an issue with the following code: https://i.stack.imgur.com/rrRhW.png This is the error message that I'm receiving: https://i.stack.imgur.com/BfNmP.png The ...

What is the best way to spy on a property being called within a function?

I am facing an issue where the 'offsetWidth' value is undefined and I need to spyOn it. The function getCurrentPage retrieves an element based on the id currentpage. Although spying on getCurrentPage works, I have been unable to declare the offs ...

leveraging two connected hooks

I am facing a challenge where I need to utilize two hooks that are interdependent: useHook1() provides a list of ids, and useHook2(id) is called for each id to retrieve a corresponding name. Essentially, what I aim to achieve is: const [allData, setData] ...

Developing a typescript React component with a generic callback event handler function passed as a prop

I'm struggling with developing a callback event handler function that can be passed down as a prop to my component. My objective: Allow users to provide a custom callback function that: always accepts the same argument an event (not a react/dom even ...

IE11 is throwing an error due to an unexpected quantifier in the regular expression

I have a string like SHM{GHT} and I need to extract the value from within the curly braces (GHT in this case). I used RegExp successfully to do this, but encountered an issue when testing on Internet Explorer. The page broke and I received an error message ...

Hold on until the page is reloaded: React

My current setup includes a React Component that contains a button. When this button is clicked, a sidePane is opened. What I want to achieve is refreshing the page first, waiting until it's completely refreshed, and then opening the sidepane. Below i ...