I have a React/TypeScript project using the Jest testing framework. Sometimes, after I update my code, Jest will compare it to the snapshots and provide an alert asking me to update them. Other times, I don't get this prompt:
Would you like to update your snapshots?
If I don’t get this prompt, I can update each individual line by hand, but this is tedious and error prone.
How do I automatically update my snapshots?
Press u to update the failing tests. However, you can also install the Jest CLI globally with npm install jest -g . This allows you to use the jest --updateSnapshot command from the terminal to update all snapshots. Personally, I prefer using Jest's interactive mode.
When writing snapshot tests for a React component, you first need to have code in a working state. Then, generate a snapshot of its expected output given certain data. The snapshot tests are committed alongside the component. Jest, a testing framework, will compare the snapshot to the rendered output for the test.
Solution #1:
For the failing test suite requiring snapshots, open a terminal and run
npm test <filename>
This will run tests just for that file. When it’s done, you have options. Hit
u
Now your tests will pass if appropriate per npm. However, Jest may not know this yet, and you may have a
// Snapshot has changed
error next to your tests. Either wait for Jest to finish running your tests, or hit the
Debug
link at the beginning of the test to clear the error.
Solution #2:
Sometimes the first solution doesn't work. Another command to run from the terminal to update snapshots is
npm run test:ci -- -u
For me the command above doesn't work. But this does:
npm test -- -u
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