javascript - Jest 单元测试函数抛出错误

标签 javascript node.js unit-testing jestjs

我试图对 Node 中的一个函数进行单元测试,无论任何条件,该函数都会抛出错误。这是我的 Node 函数定义。

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();
});

enter image description here

测试用例#2

it('Should throw test error', (done) => {
    const testClass = TestClassService.getInstance();
    expect(testClass.testFunction).toThrow();
});

enter image description here

测试用例#3

来自this博客中,有人提到

If we want to expect a function to throw an exception for certain input parameters, the key point is that we must pass in a function definition and not call our function inside the expect.

所以我将测试用例更新为

it('Should throw test error', (done) => {
    const testClass = TestClassService.getInstance();
    expect(() => testClass.testFunction()).toThrow();
});

但它抛出了类似的错误

enter image description here

我的实现存在什么问题?对抛出错误对象的函数进行单元测试的正确方法是什么?

最佳答案

你的第三次尝试是正确的。唯一的问题是您在测试定义中包含了 done 回调。这告诉测试它是异步的,并且希望您在测试完成后调用 done 回调。

由于您的测试不是异步的,因此删除测试定义中的 done 回调就足够了:

it('Should throw test error', () => {
    const testClass = TestClassService.getInstance();
    expect(() => testClass.testFunction()).toThrow();
});

关于javascript - Jest 单元测试函数抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61285655/

相关文章:

javascript - C# 如何使用 javascript 或 jquery 调用 MVC Controller 功能

node.js - Slickgrid 基本示例 - 在 node/express 中,只有第一行数据加载但不可见

node.js - 在 MongoDB 中删除时自动删除引用对象

unit-testing - 如果单元测试执行了数据库插入/更新/删除,如何检查 Play Framework

javascript - 在 HTML 中加载大表,还有什么其他可能性?

javascript - 如何获取嵌入式 Power BI 报表正在使用哪些表?

Javascript 抽屉 slider

javascript - 异步调用数据库 for 循环而不是等待

python - 单元测试 C 生成 python 代码

c# - Rhino Mocks 的新语法