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

问题描述 投票:0回答:2

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

在index.js内部:

// index.js

const UNDEFINED_ERROR = "Undefined detected.";
testFn = () => {
    try{ 
       throw new Error(UNDEFINED_ERROR);
    }catch(e){
      console.log(e);
    }
};

module.exports = {
    testFn,
    UNDEFINED_ERROR
}

在check.test.js里面:

//check.test.js

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

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

npm test之后,测试将失败,并且终端将返回Received function did not throw

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

// passed version

const UNDEFINED_ERROR = "Undefined detected.";

testFn = () => {
    throw new Error(UNDEFINED_ERROR);
};

module.exports = {
    testFn,
    UNDEFINED_ERROR
}

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

javascript unit-testing jestjs jest
2个回答
0
投票

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

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

0
投票

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

    expect(testFn).toThrow();

代替

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

问题是,testFn不应引发错误,总是会处理该错误。

应该是:

jest.spyOn(console, 'log');
testFn();
expect(console.log).toBeCalledWith(new Error("Undefined detected."));
© www.soinside.com 2019 - 2024. All rights reserved.