Skip to content

Commit eb1bf68

Browse files
authored
fix(prefer-in-document): check that a node has arguments before trying to access properties on them (#165)
* fix(prefer-in-document): handle `toHaveLength` without arguments * fix(prefer-in-document): add array length guards
1 parent 0ae17db commit eb1bf68

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

src/__tests__/lib/rules/prefer-in-document.js

+3
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,9 @@ const valid = [
3636
foo = somethingElse;
3737
expect(foo).toHaveLength(1);`,
3838
]),
39+
`expect().not.toBeNull()`,
40+
`expect(myFunction()).toBe();`,
41+
`expect(myFunction()).toHaveLength();`,
3942
`let foo;
4043
foo = "bar";
4144
expect(foo).toHaveLength(1);`,

src/rules/prefer-in-document.js

+13-4
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,10 @@ function isAntonymMatcher(matcherNode, matcherArguments) {
3232
}
3333

3434
function usesToBeOrToEqualWithNull(matcherNode, matcherArguments) {
35-
return (matcherNode.name === "toBe" || matcherNode.name === "toEqual") &&
36-
matcherArguments[0].value === null;
35+
return (
36+
(matcherNode.name === "toBe" || matcherNode.name === "toEqual") &&
37+
matcherArguments[0].value === null
38+
);
3739
}
3840

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

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

9092
// toBe() or toEqual() are only invalid with null
9193
if (matcherNode.name === "toBe" || matcherNode.name === "toEqual") {
92-
if (!usesToBeOrToEqualWithNull(matcherNode, matcherArguments)) {
94+
if (
95+
!matcherArguments.length ||
96+
!usesToBeOrToEqualWithNull(matcherNode, matcherArguments)
97+
) {
9398
return;
9499
}
95100
}
@@ -146,6 +151,10 @@ export const create = (context) => {
146151
[`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}]`](
147152
node
148153
) {
154+
if (!node.callee.object.object.arguments.length) {
155+
return;
156+
}
157+
149158
const arg = node.callee.object.object.arguments[0];
150159
const queryNode =
151160
arg.type === "AwaitExpression" ? arg.argument.callee : arg.callee;

0 commit comments

Comments
 (0)