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?
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With