【问题标题】:Using Jest to test a function which should throw an error, but always received "function did not throw" error使用 Jest 测试应该抛出错误的函数,但总是收到“函数未抛出”错误
【发布时间】:2022-03-29 05:11:41
【问题描述】:

我正在尝试为简单的 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 的新手,非常感谢这里的任何帮助!

【问题讨论】:

  • 您的错误已在 try catch 块中捕获,您不应期望 testFn 抛出错误,除非在 catch 块中重新抛出。你可以断言console.log 应该用Error 调用
  • 感谢您的指出! @Teneff 刚刚通过测试我的console.log() 解决了这个问题。真的很感激!

标签: javascript unit-testing jestjs


【解决方案1】:

如果函数不接受参数,它可以是

    expect(testFn).toThrow();

而不是

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

问题是testFn 不应该抛出错误,错误总是被处理。

应该是:

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

【讨论】:

  • 谢谢@Estus。我想你是对的。我不应该测试 throw()。问题解决了!
【解决方案2】:

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

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

【讨论】:

  • 您好,感谢您的帮助。我以前试过这个。这会给我一个Matcher error: received value must be a function 这就是我将我的函数包装在另一个函数中的原因。
  • expect 不可能以这种方式捕获错误。 testFn() 首先被评估并且未通过测试。
猜你喜欢
  • 2020-07-31
  • 2020-10-22
  • 1970-01-01
  • 2012-08-23
  • 2020-12-07
  • 1970-01-01
  • 2021-02-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多