【发布时间】:2018-01-12 03:16:04
【问题描述】:
我遇到了无法解决的单元测试问题。 这是我的测试:
fit('should call the alert service in case something went wrong getting the list of files', async(() => {
spyOn(this.component.alert, 'error');
this.component.onInputChange('error');
this.fixture.whenStable().then((() => {
expect(this.component.alert.error).toHaveBeenCalledWith('an error occured');
}));
}));
这是我正在测试的组件的一部分:
private onInputChange (search: string) {
const that = this;
this.translateFileService.getVideoFiles(search)
.then(files => (files.length) ? this.files = files : '')
.catch(this.alert.error.bind(that));
}
出于测试目的, translateFileService 被模拟如下:
class TranslateFileServiceMock {
getVideoFiles (search: string): Promise<IcoFile[]> {
const fileList = [
IcoFile.fromJSON({id: '0', label: 'test0', creationTime: '2017-07-01'}),
IcoFile.fromJSON({id: '1', label: 'test1', creationTime: '2017-07-02'}),
IcoFile.fromJSON({id: '2', label: 'test2', creationTime: '2017-07-03'}),
];
return new Promise<IcoFile[]>((resolve, reject) => {
if (search === 'error') return reject('an error occured');
return resolve(fileList.filter(f => f.label.includes(search)));
});
}
}
onInputChange 方法调用我的组件中的 alert 属性表示的警报服务。 警报服务不是模拟的,它是真正的服务。实际上调用了它的错误方法,我已经验证过了。但是我的测试总是失败:间谍没有检测到我的电话。
我总是收到以下错误:
Expected spy error to have been called with [ 'an error occured' ] but it was never called.
我不知道该怎么办。我尝试了我所知道的一切。 起初我认为我的呼叫没有被正确检测到,因为我在模拟我的警报服务,但即使是真实的,它也无法正常工作。
希望能帮到你,先谢谢了!
【问题讨论】:
-
你能添加更多代码吗?
-
完成了,如果您需要更多内容,请告诉我:)
-
你为什么在
this.component、this.fixture中使用this? -
因为它们是在我配置测试模块的 beforeEach 函数中定义的。
标签: angular unit-testing jasmine spy