Angular – unit test for a subscribe function in a component

You need this for version rxjs@6 and above. For older rxjs version answer is below:

    import { of } from 'rxjs';

    it("should call getUsers and return list of users", async(() => {
      const response: User[] = [];

      spyOn(userService, 'getUsers').and.returnValue(of(response))

      homeComponent.getUsers();

      fixture.detectChanges();
    
      expect(homeComponent.listOfUsers).toEqual(response);
    }));

For old rxjs version change import from:

    import { of } from 'rxjs';

to

    import { of } from 'rxjs/observable/of';

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)