Skip to content

Commit 35dcd13

Browse files
committed
fix: guard against type errors in prefer-t-regex
1 parent 40a81b6 commit 35dcd13

File tree

2 files changed

+34
-3
lines changed

2 files changed

+34
-3
lines changed

rules/prefer-t-regex.js

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,10 @@ const create = context => {
5151
```
5252
*/
5353
const findRootReference = node => {
54+
if (!node) {
55+
return;
56+
}
57+
5458
if (node.type === 'Identifier') {
5559
const reference = findReference(node.name);
5660

@@ -80,18 +84,27 @@ const create = context => {
8084
2. `RegExp` class can't be looked up so the function just checks for the name `RegExp`.
8185
*/
8286
const isRegExp = lookup => {
83-
if (lookup.regex) {
87+
if (lookup?.regex) {
8488
return true;
8589
}
8690

8791
// Look up references in case it's a variable or RegExp declaration.
8892
const reference = findRootReference(lookup);
93+
94+
if (!reference) {
95+
return false;
96+
}
97+
8998
return reference.regex ?? reference.name === 'RegExp';
9099
};
91100

92101
const booleanHandler = node => {
93102
const firstArg = node.arguments[0];
94103

104+
if (!firstArg) {
105+
return;
106+
}
107+
95108
const isFunctionCall = firstArg.type === 'CallExpression';
96109
if (!isFunctionCall || !firstArg.callee.property) {
97110
return;
@@ -144,6 +157,11 @@ const create = context => {
144157
}
145158

146159
const matchee = secondArgumentIsRegex ? firstArg : secondArg;
160+
161+
if (!matchee) {
162+
return;
163+
}
164+
147165
const regex = secondArgumentIsRegex ? secondArg : firstArg;
148166

149167
const booleanFixer = assertion => fixer => {
@@ -179,7 +197,12 @@ const create = context => {
179197
CallExpression: visitIf([
180198
ava.isInTestFile,
181199
ava.isInTestNode,
182-
])(node => {
200+
],
201+
)(node => {
202+
if (!node?.callee?.property) {
203+
return;
204+
}
205+
183206
const isAssertion = node.callee.type === 'MemberExpression'
184207
&& util.getNameOfRootNodeObject(node.callee) === 't';
185208

test/prefer-t-regex.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,16 @@ ruleTester.run('prefer-t-regex', rule, {
3636
header + 'test(t => t.regex(foo, RegExp(/\\d+/)));',
3737
// Shouldn't be triggered since it's not a test file
3838
'test(t => t.true(/\\d+/.test("foo")));',
39-
// Not valid, but it shouldn't cause errors
4039
'test(t => t.true());',
40+
// These shouldn't cause errors as this rule affects them.
41+
// This rule would crash on the following.
42+
header + 'test(t => t.true());',
43+
header + 'test(t => t.is(true))',
44+
header + 'test(t => t.is())',
45+
header + 'test(t => t.false())',
46+
header + 'test(t => t.falsy())',
47+
header + 'test(t => t.truthy())',
48+
header + 'test(t => t.deepEqual(true))',
4149
],
4250
invalid: [
4351
{

0 commit comments

Comments
 (0)