【发布时间】:2018-01-15 17:21:32
【问题描述】:
我正在测试我编写的加载本地 JSON 文件的组件,一切都很好并且运行良好,但我的测试并不顺利!在我的组件中,我有以下内容可以加载我在项目中使用的 JSON 列表:
public softwareList: Observable<any>;
public ngOnInit() {
this.softwareList = this.http.get('path/to/software.json').map((res: any) => {
const respJson = res.json();
return respJson.about.dependencies.software;
});
}
在我的测试中,我模拟了 JSON 和 http.get 调用的结果,一切看起来都不错 - 下面是我的测试代码...
// here's the mock...
const mockResponse = {
about: {
dependencies: {
heading: 'Software Dependencies',
explaination: 'Blah blah blah',
software: [
{
name: 'Angular & Angular Material',
url: 'https://github.com/angular'
}
]
}
}
};
// here's my test
it('should load the Software Dependencies list', async(() => {
const instance = componentFixture.componentInstance;
const spyHttpGet = sinon.spy(instance.http, 'get');
instance.ngOnInit();
expect(spyHttpGet.calledOnce).to.be.eq(true);
expect(spyHttpGet.withArgs'path/to/software.json').calledOnce).to.be.eq(true);
instance.softwareList.subscribe((res:any) => {
console.log(res); // [Object{name: 'Angular & Angular Material', url: 'https://github.com/angular'}]
expect(instance.softwareList).to.be.eq(mockResponse.about.dependencies.software);
});
}));
现在这里是最后的测试,订阅回调中的那个失败了。我收到以下错误
AssertionError: 预期 { Object (_isScalar,observers, ...) } 到 等于 [ 数组 (1) ]
从 console.log 我看到以下内容:
[Object{name: 'Angular & Angular Material', url: 'https://github.com/angular'}]
这就是我所期望的!这也是我期望instance.softwareList 的价值!我不明白为什么我的instance.softwareList 没有更新到subscribe 返回的值?我错过了什么,为什么不是instance.softwareList = [{name: 'Angular & Angular Material', url: 'https://github.com/angular'}]?
任何解释将不胜感激!
【问题讨论】:
标签: angular unit-testing mocha.js observable