【发布时间】:2019-12-09 12:56:07
【问题描述】:
如何在单元测试中模拟 throw 异常。
我尝试这样测试:expect(service.methodA).toThrowError('error');
我有这条消息:
预期函数会抛出错误匹配:
"error"。但它没有抛出任何东西。
return this.service.post(
URL,
).pipe(
map(response => response.data),
catchError(error => {
throw new Error('error');
})
).toPromise();
谢谢
【问题讨论】:
-
你试过调用这个方法吗?
expect(service.methodA()).toThrowError('error'); -
请添加更多测试,以便我们了解您是如何实施的。
-
如果 post 方法没有抛出任何东西,就没有理由触发 catchError。 return this.service.post(URL).pipe(tap(() => throw new Error('error'))).toPromise();
-
是的,但是是否可以从 Axios 模拟这个 httpService 来触发错误?在我的单元测试中,我的服务有一个间谍:
jest.spyOn(httpService, 'post').mockImplementation(() => of<AxiosResponse<ClassA>>(data));因为我必须在我的单元测试中有 100% 并且这条线没有被覆盖... -
嘿,您找到解决方案了吗?
标签: javascript typescript unit-testing vue.js