Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/435.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Jest如何测试setTimeout中抛出的错误_Javascript_Jestjs_Settimeout - Fatal编程技术网

Javascript Jest如何测试setTimeout中抛出的错误

Javascript Jest如何测试setTimeout中抛出的错误,javascript,jestjs,settimeout,Javascript,Jestjs,Settimeout,我的代码如下所示: const myFunc =() =>{ setTimeout(()=>throw new Error('err within setTimeout'),500); } 如何在Jest框架中测试抛出的错误?我看到的唯一方法是模拟setTimeout本身,使其同步运行jest.useFakeTimers()+jest.runAllTimers()可以为您做到这一点: jest.useFakeTimers(); it("throws", () =>

我的代码如下所示:

const myFunc =() =>{
    setTimeout(()=>throw new Error('err within setTimeout'),500);
}

如何在Jest框架中测试抛出的错误?

我看到的唯一方法是模拟
setTimeout
本身,使其同步运行
jest.useFakeTimers()
+
jest.runAllTimers()
可以为您做到这一点:

jest.useFakeTimers();

it("throws", () => {
  expect.assertions(1); // don't miss that to ensure exception has been thrown!
  myFunc();
  try {
    jest.runAllTimers();
  } catch(e) {
    expect(e.message).toEqual('err within setTimeout');
  }
});

我试着这么做,但没有成功。这个错误似乎是从上面传递给我的主循环scopetest中抛出的。你的实际函数看起来像你展示的吗?我认为你的代码有语法错误。至少对我来说,这段代码显示了错误:
SyntaxError:Unexpected token throw
。我认为应该是
setTimeout(()=>{throw new Error('err inthesettimeout')},500