Jest: Regex does not work with snapshot testing

Created on 4 Sep 2016  路  6Comments  路  Source: facebook/jest

Jest is amazing, thanks for all the work. I've started using snapshot testing with more than just React components and in most instances everything works perfectly.

Running version 15.1.1 with babel-jest & jest-cli. I am reporting a bug.

Steps to reproduce:

  1. Create a test file
it('should be the same regex', () => {
  const regex = /\s+ \w \d \[ \. blah.* [xyz]+/
  expect(regex).toMatchSnapshot()
  const objectContainingRegex = {regex}
  expect(objectContainingRegex).toMatchSnapshot()
})
  1. Run Jest (2 snapshots written in 1 test file.)
  2. Run Jest (2 snapshot tests failed in 1 test file.)

What was expected:

Running Jest the second time should match the snapshot.

CLI output:

image

Snapshots:

exports[`test should be the same regex 1`] = `/\s+ \w \d \[ \. blah.* [xyz]+/`;

exports[`test should be the same regex 2`] = `
Object {
  "regex": /\s+ \w \d \[ \. blah.* [xyz]+/
}
`;
Bug Help Wanted

Most helpful comment

This will be fixed in the next Jest release this week.

All 6 comments

It seems like we aren't escaping regex properly. We can fix this by introducing an option to pretty-format that will escape regex.

@cpojer pretty-format already escapes regex:

pretty-format(/\s/) === '/\\s/';
pretty-format({r: /\s/}) === 'Object {\n  "r": /\\s/,\n}';

@anilanar hm, are you sure? Is the original issue report not valid any more? If it is, would you mind sending a PR to fix it?

I am experiencing the same issue. What gets written to the snapshot file has backslashes. However when it is read back Jest doesn't see the backspaces anymore.

@cpojer I've just sent a PR with an option to escape regex with pretty-format. After fair amount of research on this issue (tried to fix this on a Jest level, but didn't succeed) it seems to be the sanest solution.

@anilanar so, pretty-format does not escape regex, it just transforms them to string (with RegEx.prototype.toString). While this is great for strings, when reading from a file all regex's backslashes must be escaped. Otherwise require call to this file will "swallow" them or escape the character after.

This will be fixed in the next Jest release this week.

Was this page helpful?
0 / 5 - 0 ratings