Skip to content

Commit

Permalink
fix(prefer-in-document): check that a node has arguments before tryin…
Browse files Browse the repository at this point in the history
…g to access properties on them (#165)

* fix(prefer-in-document): handle `toHaveLength` without arguments

* fix(prefer-in-document): add array length guards
  • Loading branch information
G-Rath authored Apr 24, 2021
1 parent 0ae17db commit eb1bf68
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
3 changes: 3 additions & 0 deletions src/__tests__/lib/rules/prefer-in-document.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ const valid = [
foo = somethingElse;
expect(foo).toHaveLength(1);`,
]),
`expect().not.toBeNull()`,
`expect(myFunction()).toBe();`,
`expect(myFunction()).toHaveLength();`,
`let foo;
foo = "bar";
expect(foo).toHaveLength(1);`,
Expand Down
17 changes: 13 additions & 4 deletions src/rules/prefer-in-document.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,10 @@ function isAntonymMatcher(matcherNode, matcherArguments) {
}

function usesToBeOrToEqualWithNull(matcherNode, matcherArguments) {
return (matcherNode.name === "toBe" || matcherNode.name === "toEqual") &&
matcherArguments[0].value === null;
return (
(matcherNode.name === "toBe" || matcherNode.name === "toEqual") &&
matcherArguments[0].value === null
);
}

function usesToHaveLengthZero(matcherNode, matcherArguments) {
Expand Down Expand Up @@ -71,7 +73,7 @@ export const create = (context) => {
if (!queryNode || (!queryNode.name && !queryNode.property)) return;

// toHaveLength() is only invalid with 0 or 1
if (matcherNode.name === "toHaveLength") {
if (matcherNode.name === "toHaveLength" && matcherArguments.length) {
const lengthValue = getLengthValue(matcherArguments);
// isNotToHaveLengthZero represents .not.toHaveLength(0) which is a valid use of toHaveLength
const isNotToHaveLengthZero =
Expand All @@ -89,7 +91,10 @@ export const create = (context) => {

// toBe() or toEqual() are only invalid with null
if (matcherNode.name === "toBe" || matcherNode.name === "toEqual") {
if (!usesToBeOrToEqualWithNull(matcherNode, matcherArguments)) {
if (
!matcherArguments.length ||
!usesToBeOrToEqualWithNull(matcherNode, matcherArguments)
) {
return;
}
}
Expand Down Expand Up @@ -146,6 +151,10 @@ export const create = (context) => {
[`CallExpression[callee.object.object.callee.name='expect'][callee.object.property.name='not'][callee.property.name=${alternativeMatchers}], CallExpression[callee.object.callee.name='expect'][callee.object.property.name='not'][callee.object.arguments.0.argument.callee.name=${alternativeMatchers}]`](
node
) {
if (!node.callee.object.object.arguments.length) {
return;
}

const arg = node.callee.object.object.arguments[0];
const queryNode =
arg.type === "AwaitExpression" ? arg.argument.callee : arg.callee;
Expand Down

0 comments on commit eb1bf68

Please sign in to comment.