简体   繁体   English

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

[英]Using Jest to test a function which should throw an error, but always received “function did not throw” error

I was trying to write a unit test for a simple try-catch structure function.我试图为简单的 try-catch 结构 function 编写单元测试。 My function is in index.js, and the test is in check.test.js.我的function在index.js,测试在check.test.js。 I am not sure what caused this issue.我不确定是什么导致了这个问题。

Inside of index.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
}

Inside of check.test.js:在 check.test.js 内部:

//check.test.js

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

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

After npm test , the test will fail and the terminal will give back Received function did not throw . npm test后,测试失败,终端将返回Received function did not throw

I referenced this similar question , it will perfectly run and pass after deleting try-catch in function, which is just我引用了这个类似的问题,它会在删除function中的try-catch后完美运行并通过,这只是

// passed version

const UNDEFINED_ERROR = "Undefined detected.";

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

module.exports = {
    testFn,
    UNDEFINED_ERROR
}

I am a rookie for JS and Jest and I am really appreciate any help here!我是 JS 和 Jest 的新手,非常感谢这里的任何帮助!

If the function doesn't accept components, it can be如果 function 不接受组件,则可以

    expect(testFn).toThrow();

instead of代替

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

The problem is that testFn isn't supposed to throw an error, the error is always handled.问题是testFn不应该抛出错误,错误总是被处理。

It should be:它应该是:

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

You don't need to wrap your function call in another method.您不需要用另一种方法包装您的 function 调用。 You were testing that this "wrapper method" was throwing instead of your function itself.您正在测试这个“包装器方法”而不是您的 function 本身。 Try this:尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM