Skip to content

Commit

Permalink
fix: guard against type errors in prefer-t-regex
Browse files Browse the repository at this point in the history
  • Loading branch information
spence-s committed Jan 16, 2023
1 parent 40a81b6 commit fbfd313
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 8 deletions.
16 changes: 8 additions & 8 deletions rules/prefer-t-regex.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ const create = context => {
```
*/
const findRootReference = node => {
if (node.type === 'Identifier') {
if (node?.type === 'Identifier') {
const reference = findReference(node.name);

if (reference?.init) {
Expand All @@ -61,11 +61,11 @@ const create = context => {
return node;
}

if (node.type === 'CallExpression' || node.type === 'NewExpression') {
if (node?.type === 'CallExpression' || node?.type === 'NewExpression') {
return findRootReference(node.callee);
}

if (node.type === 'MemberExpression') {
if (node?.type === 'MemberExpression') {
return findRootReference(node.object);
}

Expand All @@ -80,19 +80,19 @@ const create = context => {
2. `RegExp` class can't be looked up so the function just checks for the name `RegExp`.
*/
const isRegExp = lookup => {
if (lookup.regex) {
if (lookup?.regex) {
return true;
}

// Look up references in case it's a variable or RegExp declaration.
const reference = findRootReference(lookup);
return reference.regex ?? reference.name === 'RegExp';
return reference?.regex ?? reference?.name === 'RegExp';
};

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

const isFunctionCall = firstArg.type === 'CallExpression';
const isFunctionCall = firstArg?.type === 'CallExpression';
if (!isFunctionCall || !firstArg.callee.property) {
return;
}
Expand Down Expand Up @@ -156,7 +156,7 @@ const create = context => {
};

// Only fix a statically verifiable equality.
if (regex && matchee.type === 'Literal') {
if (regex && matchee?.type === 'Literal') {
let assertion;

if (matchee.raw === 'true') {
Expand All @@ -180,7 +180,7 @@ const create = context => {
ava.isInTestFile,
ava.isInTestNode,
])(node => {
const isAssertion = node.callee.type === 'MemberExpression'
const isAssertion = node.callee?.type === 'MemberExpression'
&& util.getNameOfRootNodeObject(node.callee) === 't';

const isBooleanAssertion = isAssertion
Expand Down
3 changes: 3 additions & 0 deletions test/prefer-t-regex.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ ruleTester.run('prefer-t-regex', rule, {
'test(t => t.true(/\\d+/.test("foo")));',
// Not valid, but it shouldn't cause errors
'test(t => t.true());',
// Not valid, but it shouldn't cause errors
header + 'test(t => t.is(true))',
header + 'test(t => t.is())',
],
invalid: [
{
Expand Down

0 comments on commit fbfd313

Please sign in to comment.