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.
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 | });
All of the above tests should pass.
https://repl.it/repls/KaleidoscopicBuzzingEnvironment
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
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.
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.