繁体   English   中英

Jest - 测试 try/catch

[英]Jest - testing try/catch

我正在尝试测试此类方法:

get () {
  try {
    return 'value'
  } catch (e) {
    return 'value2'
  }
}

和:

test('the get method retrieves value', () => {
  const value = MyClass.get()
  expect(value).toBe('value')
})

我的测试覆盖率显示我已经测试了方法的try部分,但没有测试catch部分。

我怎样才能覆盖catch部分?

您可以通过将函数调用包装在测试中的try catch块中期待断言来测试 catch 部分。 在不期望断言的情况下,不会导致错误的测试运行仍将通过。

https://jestjs.io/docs/en/tutorial-async#error-handling

test('the fetch fails with an error', async done => {
  expect.assertions(1);
  try {
    await fetchData();
  } catch (e) {
    expect(e).toMatch('error');
  }
});

您可以将期望包装在 setImmediate() 或 process.nextTick() 中:

test('the fetch fails with an error', async => {
  expect.assertions(1);
  setImmediate(() => {
   expect(fetchData).toMatch('error');
  });
});

请试试这个:

  test('the fetch fails with an error', async () => {
    expect(() => {
      await fetchData();
    }).toThrow();
  });

更多信息: https : //jestjs.io/docs/en/expect#tothrowerror

暂无
暂无

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

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