【发布时间】:2020-10-13 11:43:00
【问题描述】:
显然,我仍然缺少对模拟服务的重要理解,我很乐意提供一些意见。
我想在我的组件中测试的代码是:
modulesToDisplay: any[] = [];
...
getModules() {
this.configService.getModulesToDisplay().subscribe(modules => {
this.modulesToDisplay = modules;
}
);
}
我想测试当我从服务中获取某些内容时是否重新分配了 modulesToDisplay。因此,在我的 Testfile 中,我创建了一个 serviceMock,它返回一个包含两个项目的数组
let configServiceMock: any;
...
beforeEach(async(() => {
configServiceMock = jasmine.createSpyObj('ConfigService', ['getModulesToDisplay']);
configServiceMock.getModulesToDisplay.and.returnValue( of(['firstmodule', 'secondmodule']) );
...
providers: [
{ ConfigService, useValue: configServiceMock }
]
}).compileComponents();
beforeEach(() => {
fixture = TestBed.createComponent(SomeComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should assign result to modulesToDisplay', () => {
component.getModules();
expect(component.modulesToDisplay.length).toBeGreaterThan(0);
});
...
我希望这个测试能够通过,因为我认为调用 'component.getModules();'在我的测试中将使用模拟数据。但它没有,modulesToDisplay 仍然是我在组件中初始化的空数组。所以我想我还是没有理解 mocking 数据的正确原理。
【问题讨论】:
标签: javascript angular typescript unit-testing karma-jasmine