Skip to content

Commit b0a252d

Browse files
authored
fix: escape special chars in regex for toHaveTextContent fixer (#68)
1 parent 875e6b1 commit b0a252d

File tree

2 files changed

+40
-3
lines changed

2 files changed

+40
-3
lines changed

src/__tests__/lib/rules/prefer-to-have-text-content.js

+30-1
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,26 @@ ruleTester.run("prefer-to-have-text-content", rule, {
8484
],
8585
output: `expect(element).toHaveTextContent(/foo/)`,
8686
},
87+
{
88+
code: 'expect(element.textContent).toContain("$42/month?")',
89+
errors: [
90+
{
91+
message:
92+
"Use toHaveTextContent instead of asserting on DOM node attributes",
93+
},
94+
],
95+
output: "expect(element).toHaveTextContent(/\\$42\\/month\\?/)",
96+
},
97+
{
98+
code: "expect(element.textContent).toContain(100)",
99+
errors: [
100+
{
101+
message:
102+
"Use toHaveTextContent instead of asserting on DOM node attributes",
103+
},
104+
],
105+
output: `expect(element).toHaveTextContent(/100/)`,
106+
},
87107
{
88108
code: 'expect(container.firstChild.textContent).toContain("foo")',
89109
errors: [
@@ -165,7 +185,6 @@ ruleTester.run("prefer-to-have-text-content", rule, {
165185
],
166186
output: "expect(element).not.toHaveTextContent(/foo bar/)",
167187
},
168-
169188
{
170189
code: 'expect(element.textContent).not.toMatch("foo")',
171190
errors: [
@@ -176,5 +195,15 @@ ruleTester.run("prefer-to-have-text-content", rule, {
176195
],
177196
output: `expect(element).not.toHaveTextContent(/foo/)`,
178197
},
198+
{
199+
code: 'expect(element.textContent).not.toMatch("$42/month?")',
200+
errors: [
201+
{
202+
message:
203+
"Use toHaveTextContent instead of asserting on DOM node attributes",
204+
},
205+
],
206+
output: `expect(element).not.toHaveTextContent(/\\$42\\/month\\?/)`,
207+
},
179208
],
180209
});

src/rules/prefer-to-have-text-content.js

+10-2
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,11 @@ export const create = (context) => ({
3636
expectedArg.type === "Literal"
3737
? expectedArg.regex
3838
? expectedArgSource
39-
: `/${expectedArg.value}/`
39+
: new RegExp(
40+
expectedArg.value
41+
.toString()
42+
.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&")
43+
)
4044
: `new RegExp(${expectedArgSource})`
4145
),
4246
];
@@ -92,7 +96,11 @@ export const create = (context) => ({
9296
expectedArg.type === "Literal"
9397
? expectedArg.regex
9498
? expectedArgSource
95-
: `/${expectedArg.value}/`
99+
: new RegExp(
100+
expectedArg.value
101+
.toString()
102+
.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&")
103+
)
96104
: `new RegExp(${expectedArgSource})`
97105
),
98106
],

0 commit comments

Comments
 (0)