Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I update the snapshots in my React/TypeScript project?

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?

Alert: 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?

like image 624
Super Jade Avatar asked Jun 25 '19 22:06

Super Jade


People also ask

How do you update a snapshot in React?

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.

How do I use snapshot in React?

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.


Video Answer


2 Answers

Run Jest from the terminal instead

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
like image 91
Super Jade Avatar answered Oct 04 '22 17:10

Super Jade


For me the command above doesn't work. But this does:

npm test -- -u
like image 44
Cublax Avatar answered Oct 04 '22 17:10

Cublax