使用React,Jest,React-Testing-Library测试失败的案例

Naj*_*aji 1 javascript unit-testing reactjs jestjs

我有一个React组件,当编程错误时会抛出一个错误。例如,组件Component采用所需的prop data,我有:

if (!data) { throw new Error("data is not provided") }

写在我的组件中以处理此错误。使用jest我的测试说:

test("throw invalid component error", () => {
    mockConsole();
    const { container } = render(<Component />);
    expect(container).toThrowError();
});
Run Code Online (Sandbox Code Playgroud)

当我运行测试时,Jest说测试失败,然后它指向我throw new Error(...)编写代码的那一行。我在开玩笑地想做些什么吗?

lip*_*ipp 5

要断言a function引发错误,您必须将a传递function给Expect语句。在您的情况下:

test('...', () => {
  expect(() => {
    render(<Component />);
  }).toThrowError();
});
Run Code Online (Sandbox Code Playgroud)