I have a simple Jest snapshot test, and upon failure, I would like to print a custom error message to remind the developer that if they intentionally failed the test, they need to ensure they update a related constant that's used in the page/component. Here is my test:
describe('My Page', () => {
it('matches the snapshot', () => {
const { asFragment } = render(<MyComponent />)
expect(asFragment()).toMatchSnapshot()
})
})
I've tried to wrap the expect
in a try/catch, however, the test fails immediately at toMatchSnapshot()
and the catch block is never reached:
try {
expect(asFragment()).toMatchSnapshot()
} catch (error) {
error.message +=
'\nNOTE: The snapshot for the page has changed. If this is intentional, please remember to update the MY_CONSTANT constant accordingly.'
throw error
}
Is there any way to print a custom error message when a Jest snapshot test fails?