我正在测试我编写的加载本地 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: expected { Object (_isScalar, observers, ...( } to 等于 [ 数组(1( ]
从控制台.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'}]
?
任何解释将不胜感激!
你影响了 ngOnInit 中的 softwareList: this.softwareList = this.http.get
所以软件列表有一个可观察的签名:
对象(_isScalar、观察者等(
为了通过测试,您可以断言可观察量的响应:
expect(res).to.be.eq(mockResponse.about.dependencies.software);