【发布时间】: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