0
votes

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!

1
I am thinking you may need another tick() after the first one. In the test, right before the expect(msService.serviceMethod).toHaveBeenCalledWith(params) add a console.log of doing assertion and in the componentToTest method add a log of calling service right before the this.service.serviceMethod call. Ensure you see both logs and to make the test pass, make sure you see calling service before doing assertion.AliF50
Thank you for your comment! I fixed itkleo

1 Answers

0
votes

I fixed it myself. In privateComponentMethod, there was another service async method call. I hadn't mocked the service nor spied on the service method. I mocked the service and the method as a Partial and let the method return a new resolved promise of the suitable type. I then spied on the method and let it return a promise.