javascript - Jest 单元测试函数抛出错误
问题描述
我试图对节点中的一个函数进行单元测试,该函数在任何条件下都会引发错误。这是我的节点函数定义。
public testFunction() {
throw new Error('Test Error');
}
正如你所看到的,这个函数在被调用时总是抛出一个错误。我尝试使用 jest .toThrow(error?)方法对此函数执行单元测试。我无法按预期对功能进行单元测试。
下面提到的是我编写的测试用例,并附上了我在执行相同时遇到的错误的屏幕截图。
测试用例 #1
it('Should throw test error', (done) => {
const testClass = TestClassService.getInstance();
expect(testClass.testFunction()).toThrow();
});
测试用例 #2
it('Should throw test error', (done) => {
const testClass = TestClassService.getInstance();
expect(testClass.testFunction).toThrow();
});
测试用例 #3
从这个博客中,有人提到
如果我们希望函数对某些输入参数抛出异常,关键是我们必须传入一个函数定义,而不是在期望中调用我们的函数。
所以我将我的测试用例更新为
it('Should throw test error', (done) => {
const testClass = TestClassService.getInstance();
expect(() => testClass.testFunction()).toThrow();
});
但它抛出了错误,比如
我的实施有什么问题?对抛出错误对象的函数进行单元测试的正确方法是什么?
解决方案
您在第三次尝试中做对了。唯一的问题是您done
在测试定义中包含回调。这告诉测试它是异步的,并且它希望您done
在测试完成后调用回调。
由于您的测试不是异步的,因此删除done
测试定义中的回调就足够了:
it('Should throw test error', () => {
const testClass = TestClassService.getInstance();
expect(() => testClass.testFunction()).toThrow();
});
推荐阅读
- c# - 在 ASP.NET MVC 5 启动类中注入依赖项
- jquery - 使用 jquery 获取价值
- javascript - 如何将数据从 html 发送到 node.js
- regex - 选择 PRIMARY KEY (`role_id`) 后的字符
- java - 指针如何在单链表中工作?
- azure - Office 365 - 将托管域切换到联合域会导致访问/刷新令牌失效吗?
- javascript - 每 x 次创建 img
- java - Java - 打印 10 亿到 20 亿
- git - 为什么我在 git 上出现错误,但在 rebar3 中却没有 hex deps
- weather-api - 如何编写一个简单的天气检查应用程序?