Jasmine Unit Case 具有订阅的组件方法返回未定义并且总是失败
我的组件具有以下方法:
get(): void {
this.service.get().subscribe((res) => {
this.response = res;
});
}
我有以下测试用例:
it('should get content ', () => {
const currentObject = {};
spyOn(service, 'get').and.returnValue(of(currentObject));
component.get();
fixture.detectChanges();
expect(component.response).toEqual(currentObject);
});
结果始终是:
预期未定义等于 Object({ })。
这里有很多与此相关的类似问题,但由于某种原因,这些问题都不适合我。
My component has the following method:
get(): void {
this.service.get().subscribe((res) => {
this.response = res;
});
}
I have the following test case for it:
it('should get content ', () => {
const currentObject = {};
spyOn(service, 'get').and.returnValue(of(currentObject));
component.get();
fixture.detectChanges();
expect(component.response).toEqual(currentObject);
});
The result is always:
Expected undefined to equal Object({ }).
There are plenty of similar questions regarding this here but for someone reason none of those work for me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为这可能是由于代码的异步性质所致,其中
.subscribe
在您的expect
之后发生。尝试这样进行调试:
确保您在
这应该发生在最后
之前看到这应该首先发生
。我认为解决这个问题的一个潜在方法可能是使用
fakeAsync/tick
。I am thinking this could be due to the asynchronous nature of the code where
.subscribe
happens after yourexpect
.Try this to debug:
Make sure you see
This should happen first
beforeThis should happen last
.I think a potential way to fix it is maybe using
fakeAsync/tick
.