Search code examples
typescriptunit-testingnpmvisual-studio-codejestjs

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?


Solution

  • 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