typescript – How to mock service function in Angular component for unit test

typescript – How to mock service function in Angular component for unit test

Try updating providers inside beforeEach(async(() => …) and moving your mockedService variable on the top of it:

describe(Component TEST, () => {
   ...
   let mockToolBarService;
   ...
      beforeEach(async(() => {
      ...
      mockToolBarService = jasmine.createSpyObj([getCustomer]);
      mockToolBarService.getCustomer.and.returnValue(king);
      TestBed.configureTestingModule ({
           ...
           providers: [ { provide: TopToolBarService, useValue: mockToolBarService } ]
           ...

Hope it helps!

Change your provider value

beforeEach(() => {
   TestBed.configureTestingModule({
      declarations: [ UsersListComponent],
      providers: [{
         provide: TopToolBarService,
         useValue: jasmine.createSpyObj(TopToolBarService, [getCustomer])
      }],
      schemas:[CUSTOM_ELEMENTS_SCHEMA]
     });
     mockTopToolBarService = TestBed.get(TopToolBarService);

     mockTopToolBarService.getCustomer.and.returnValue(of([])); // mock output of function
   })

typescript – How to mock service function in Angular component for unit test

The answer from @Pedro Bezanilla is good enough. Just heres another way with less code, given the service is a singleton, which I think is most of the case.

The difference is that theres no provider configuration given to configureTestingModule. The spy is set up by spyOn against the service object taken from TestBed instead.

Calling TestBed.inject instead of TestBed.get is because it is deprecated since v9.0.0.

For singleton services, heres a doc in Angular website, and for completion, keep it in mind this GitHub issue.

describe(Component TEST, () => {
  ...
  let mockToolBarService: TopToolBarService;
  ...
  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      declarations: [ UsersListComponent ],
      schemas:[ CUSTOM_ELEMENTS_SCHEMA ]
    });
    mockTopToolBarService = TestBed.inject(TopToolBarService);
    spyOn(mockTopToolBarService, getCustomer).and.returnValue(of([]));
  }));
  ...

Leave a Reply

Your email address will not be published.