测试 angular 组件:我如何测试在 Jasmine 中使用 expect(method).toHaveBeenCalledWith(p) 进行异步方法调用之后的方法调用

Testing angular components: how can I test method call that comes after an async method call with expect(method).toHaveBeenCalledWith(p) in Jasmine

我正在尝试使用 jasmine 测试异步组件方法。此方法随后调用另一个私有异步组件方法和服务方法。我想测试服务方法调用,但不断收到错误消息“

expected serviceMethod to have been called with ... but it was never called

这是我要测试的组件方法:

public async componentMethodToTest(): Promise<void> {

  await this.privateComponentMethod(param);

  this.service.serviceMethod([
  { key: 'str_1', value: 'val_1' },
  { key: 'str_2', value: 'val_2' }
  ]);

}

我尝试过的:

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);
}));

在此先感谢您!

我自己修好了。在 privateComponentMethod 中,还有另一个服务异步方法调用。我没有嘲笑服务,也没有监视服务方法。我将服务和方法模拟为 Partial,并让方法 return 成为合适类型的新解析承诺。然后我监视这个方法并让它 return 一个承诺。