Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test failing cases with React, Jest, React-Testing-Library

I have a React component that throws an Error when programming is wrong. For example, the component Component takes the required prop data, and I have:

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

written in my component to handle this error. Using jest my test says:

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

When I run my test Jest says that the test fails and then it points me to the line where I have my throw new Error(...) written. Is what I'm trying to do possible in jest?

like image 385
Naji Avatar asked Jun 04 '18 20:06

Naji


1 Answers

To assert a function to throw an error, you have to pass a function to the expect statement. In your case:

test('...', () => {
  expect(() => {
    render(<Component />);
  }).toThrowError();
});
like image 98
lipp Avatar answered Sep 17 '22 18:09

lipp