Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Jest snapshots contain escaping characters because of double quotes?

Something in Jest seems weird to me. Is that normal that this line:

expect(`"Hello"`).toMatchSnapshot();

Gives me the following snapshot:

exports[`Item renders and matches the snapshot 1`] = `"\\"Hello\\""`;

I would expect the snapshot to be just "Hello" and not "\\"Hello\\"". Is that an issue or is there something behind that I don't understand?

like image 392
Thomas Lombart Avatar asked Jul 06 '19 07:07

Thomas Lombart


People also ask

What is the point of snapshot testing?

Snapshot tests are useful when you want to make sure your UI does not change unexpectedly. A typical snapshot test case renders a UI component, takes a snapshot, then compares it to a reference snapshot file stored alongside the test.

Should I commit jest snapshots?

Yes, all snapshot files should be committed alongside the modules they are covering and their tests. They should be considered part of a test, similar to the value of any other assertion in Jest.

How do I update a snapshot in jest?

You should then update the snapshot tests. Note: Alternatively, if you have Jest installed globally, you can run jest --updateSnapshot or jest -u . This will update the snapshots to match the updates you made, and your tests will pass.


1 Answers

snapshots are based on JSON.stringify, if you run your browser devtools:

JSON.stringify("hello"); // outputs: '"hello"'

as you can see, we have the extra single quote to wrap the double quote

jest uses the same approach, but since it uses double quote wrapping for results of snapshots, it needs to escape your value to be able to wrap it with double quotes, hence "\\"Hello\\"".

like image 94
oieduardorabelo Avatar answered Oct 06 '22 00:10

oieduardorabelo