【问题标题】:Testing angular components: how can I test method call that comes after an async method call with expect(method).toHaveBeenCalledWith(p) in Jasmine测试角度组件:如何在 Jasmine 中使用 expect(method).toHaveBeenCalledWith(p) 测试异步方法调用之后的方法调用
【发布时间】:2021-03-02 17:12:02
【问题描述】:

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

预计 serviceMethod 会被调用 ... 但它从来没有 叫

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

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

非常感谢您!

【问题讨论】:

  • 我认为您可能需要在第一个tick() 之后。在测试中,在expect(msService.serviceMethod).toHaveBeenCalledWith(params) 之前添加doing assertion 的console.log 并在componentToTest 方法中在this.service.serviceMethod 调用之前添加calling service 的日志。确保您看到这两个日志并通过测试,请确保您在 doing assertion 之前看到 calling service

标签: angular jasmine karma-jasmine


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-21
    • 2020-02-19
    相关资源
    最近更新 更多