使用Jest测试应该抛出错误但总是收到“函数未抛出”错误的函数

时间:2020-06-13 00:19:00

标签: javascript unit-testing jestjs

我试图为一个简单的try-catch结构函数编写一个单元测试。我的功能在index.js中,测试在check.test.js中。我不确定是什么引起了这个问题。

在index.js内部:

//check.test.js

const {testFn, UNDEFINED_ERROR} = require('./src/index');

describe('test', ()=>{
    it('show throw',()=>{
        expect(()=>{
          testFn();
        }).toThrow();
    });
});

在check.test.js里面:

npm test

Received function did not throw之后,测试将失败,终端将退还// passed version const UNDEFINED_ERROR = "Undefined detected."; testFn = () => { throw new Error(UNDEFINED_ERROR); }; module.exports = { testFn, UNDEFINED_ERROR }

我引用了此similar question,它会在删除try-catch函数后完美运行并通过

System.InvalidCastException: 'Conversion from type 'TranslationResult' to type 'String' is not valid.'

我是JS和Jest的新手,非常感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

如果该函数不接受组件,则可以

    expect(testFn).toThrow();

代替

    expect(() => testFn()).toThrow();

问题在于testFn不应该引发错误,该错误总是可以处理的。

应该是:

jest.spyOn(console, 'log');
testFn();
expect(console.log).toBeCalledWith(new Error("Undefined detected."));

答案 1 :(得分:0)

您不需要将函数调用包装在另一个方法中。您正在测试抛出该“包装方法”而不是函数本身。试试这个:

describe('test', ()=>{
    it('show throw',()=>{
        expect(testFn()).toThrow();
    });
});