Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make Jest test for a thrown error silently

I’m writing a test to assert that a component throws an error if provided one prop but not another.

The test itself passes, but the console still complains about an uncaught error and prints the entire stack trace. Is there a way I can get Jest to stop printing this information, as it pollutes the test runner and makes it look like something has failed.

For reference, this is my test:

it("throws an error if showCancel is set to true, but no onCancel method is provided", () => {
    // Assert that an error is thrown
    expect(() => mount(<DropTarget showCancel={ true }/>)).toThrowError("If `showCancel` is true, you must provide an `onCancel` method");
});

The error itself is thrown here:

if(props.showCancel && !props.onCancel) {
    throw new Error("If `showCancel` is true, you must provide an `onCancel` method");
}
like image 384
Jordan Garvey Avatar asked Feb 18 '19 16:02

Jordan Garvey


1 Answers

I found the one line answer to my issue here.

Adding spyOn(console, "error"); (in the test that expects an error) suppresses the error from being logged.

like image 168
Jordan Garvey Avatar answered Oct 12 '22 14:10

Jordan Garvey