1

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?

1
  • This may help. Commented Feb 7 at 11:53

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.