I'm trying to test an async component method using jasmine. This method calls another private async component method and a service method afterwards. I wanna test the service method call but keep getting the error "
expected
serviceMethod
to have been called with ... but it was never called
This is the component method I'm trying to test:
public async componentMethodToTest(): Promise<void> { await this.privateComponentMethod(param); this.service.serviceMethod([ { key: 'str_1', value: 'val_1' }, { key: 'str_2', value: 'val_2' } ]); }
What I have tried:
describe('Component', () => { let component: Component; let fixture: ComponentFixture<Component>; const mService = jasmine.createSpyObj('Service', ['serviceMethod']); beforeEach(async(() => { TestBed.configureTestingModule({ schemas: [CUSTOM_ELEMENTS_SCHEMA] providers: [ { provide: Service, useValue: mService }, ] }) .compileComponents(); }));
beforeEach(() => { fixture = TestBed.createComponent(Component); component = fixture.componentInstance; fixture.detectChanges(); });
it('should do stuff', fakeAsync(() => { mService.serviceMethod.and.callThrough(); const params = [ { key: 'str_1', value: 'val_1' }, { key: 'str_2', value: 'val_2' } ] component.componentMethodToTest(); tick(); fixture.detectChanges(); expect(mService.serviceMethod).toHaveBeenCalledWith(params); }));
Thank you so much in advance!
tick()
after the first one. In the test, right before theexpect(msService.serviceMethod).toHaveBeenCalledWith(params)
add a console.log ofdoing assertion
and in thecomponentToTest
method add a log ofcalling service
right before thethis.service.serviceMethod
call. Ensure you see both logs and to make the test pass, make sure you seecalling service
beforedoing assertion
. – AliF50