Jest: toMatch behaves oddly for regex with global flag

Created on 8 Dec 2019  路  2Comments  路  Source: facebook/jest

馃悰 Bug Report

We're upgrading from Jest 23 to 24 and encountered an odd breaking test. When testing a RegExp with the g flag, the regular expression is not reset between assertions, such that subsequent assertions that should pass, fail.

This test passes on Jest 23. It appears this behavior was introduced in c3a01676b06e9b2372ef7d883256c6745ba3c25c. Previously, Jest used new RegExp(expected).test(received), but switched to expected.test(received). This causes confusing behavior due to the way that regular expressions with the g or y flag keep a lastIndex.

To Reproduce

Steps to reproduce the behavior:

We have a regex /[f]\d+/ig which matches all instances in a string. In our tests, we test it against several strings:

it('matches on acceptable string formats', () => {
  const regex = /[f]\d+/ig;
  expect('f567').toMatch(regex);
  expect('F12 + 2 / f45').toMatch(regex);
  expect('Ff567').toMatch(regex);
  expect('f1 2').toMatch(regex);
  expect('F12abc + 123 + gf123').toMatch(regex);
});

This reports:

    Expected pattern: /[f]\d+/gi
    Received string:  "Ff567"

      72 |     expect('f567').toMatch(regex);
      73 |     expect('F12 + 2 / f45').toMatch(regex);
    > 74 |     expect('Ff567').toMatch(regex);
         |                     ^
      75 |     expect('f1 2').toMatch(regex);
      76 |     expect('F12abc + 123 + gf123').toMatch(regex);
      77 |   });

Expected behavior

All of the above tests should pass.

Link to repl or repo (highly encouraged)

https://repl.it/repls/KaleidoscopicBuzzingEnvironment

envinfo

  System:
    OS: Linux 4.15 Linux Mint 18.3 (Sylvia)
    CPU: (8) x64 Intel(R) Xeon(R) CPU E3-1505M v5 @ 2.80GHz
  Binaries:
    Node: 10.15.0 - ~/.nvm/versions/node/v10.15.0/bin/node
    Yarn: 1.19.2 - /usr/bin/yarn
    npm: 6.4.1 - ~/.nvm/versions/node/v10.15.0/bin/npm
  npmPackages:
    jest: ^24.9.0 => 24.9.0
Bug Report Confirmed Help Wanted good first issue

Most helpful comment

@jeysal Sure, I can give it a try. Not sure how soon I'll get to it, though, so if somebody else comes along and wants to take it, feel free.

All 2 comments

Confirmed. cc @pedrottimark
@mockdeep would you like to try and submit a PR with fix+regression test? :)

@jeysal Sure, I can give it a try. Not sure how soon I'll get to it, though, so if somebody else comes along and wants to take it, feel free.

Was this page helpful?
0 / 5 - 0 ratings