Skip to content

Commit 40aaadc

Browse files
authored
prefer-t-regex: Prevent some type errors (#350)
1 parent 40a81b6 commit 40aaadc

File tree

2 files changed

+37
-2
lines changed

2 files changed

+37
-2
lines changed

rules/prefer-t-regex.js

+28-1
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,31 @@ 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 => {
87+
if (!lookup) {
88+
return false;
89+
}
90+
8391
if (lookup.regex) {
8492
return true;
8593
}
8694

8795
// Look up references in case it's a variable or RegExp declaration.
8896
const reference = findRootReference(lookup);
97+
98+
if (!reference) {
99+
return false;
100+
}
101+
89102
return reference.regex ?? reference.name === 'RegExp';
90103
};
91104

92105
const booleanHandler = node => {
93106
const firstArg = node.arguments[0];
94107

108+
if (!firstArg) {
109+
return;
110+
}
111+
95112
const isFunctionCall = firstArg.type === 'CallExpression';
96113
if (!isFunctionCall || !firstArg.callee.property) {
97114
return;
@@ -144,6 +161,11 @@ const create = context => {
144161
}
145162

146163
const matchee = secondArgumentIsRegex ? firstArg : secondArg;
164+
165+
if (!matchee) {
166+
return;
167+
}
168+
147169
const regex = secondArgumentIsRegex ? secondArg : firstArg;
148170

149171
const booleanFixer = assertion => fixer => {
@@ -179,7 +201,12 @@ const create = context => {
179201
CallExpression: visitIf([
180202
ava.isInTestFile,
181203
ava.isInTestNode,
182-
])(node => {
204+
],
205+
)(node => {
206+
if (!node?.callee?.property) {
207+
return;
208+
}
209+
183210
const isAssertion = node.callee.type === 'MemberExpression'
184211
&& util.getNameOfRootNodeObject(node.callee) === 't';
185212

test/prefer-t-regex.js

+9-1
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)