据我所知,茉莉花的.toHaveBeenCalled()
匹配器会返回一个Promise,当调用该函数时,该Promise将被解决。实际上,对于我来说,它返回未定义的值:
it('should show the first entries', () => {
expect(contentfulService.first)
.toHaveBeenCalled()
.then(() => {
expect(component.entries).toBe(entriesMock);
});
});
contentfulService的first
方法是这样监视的:
contentfulService = TestBed.get(ContentfulService);
spyOn(contentfulService, 'first').and.callThrough();
规范无法告诉我:
TypeError:无法读取未定义的属性'then'
我仔细检查了一下。肯定是toHaveBeenCalled()
返回未定义的结果。为什么?我有什么问题吗?
答案 0 :(得分:3)
toHaveBeenCalled
是一种断言方法(例如toBe
或toEqual
)。这是一种同步方法,如果尚未调用该模拟程序,则测试失败,并且该方法返回undefined。
通常,您在测试结束时调用它,以验证您的代码是否达到了预期的效果。不能用于流量控制。