From 4bb038535090dc98f9aba206a90f7b414cb61157 Mon Sep 17 00:00:00 2001 From: Gareth Jones Date: Sat, 24 Apr 2021 13:45:08 +1200 Subject: [PATCH] fix(createBannedAttributeRule): check arguments length before accessing --- .../__fixtures__/createBannedAttributeTestCases.js | 10 ++++++++++ src/createBannedAttributeRule.js | 7 ++++++- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/__tests__/__fixtures__/createBannedAttributeTestCases.js b/src/__tests__/__fixtures__/createBannedAttributeTestCases.js index 34341d1..957b70d 100644 --- a/src/__tests__/__fixtures__/createBannedAttributeTestCases.js +++ b/src/__tests__/__fixtures__/createBannedAttributeTestCases.js @@ -3,6 +3,15 @@ export default ({ preferred, negatedPreferred, attribute }) => { const doubleNegativeCases = negatedPreferred.startsWith("toBe") ? [ + { + code: `expect().not.${negatedPreferred}`, + errors: [ + { + message: `Use ${preferred} instead of not.${negatedPreferred}`, + }, + ], + output: `expect().${preferred}`, + }, { code: `const el = screen.getByText("foo"); expect(el).not.${negatedPreferred}`, errors: [ @@ -66,6 +75,7 @@ export default ({ preferred, negatedPreferred, attribute }) => { return { valid: [ + `expect().not.toHaveProperty('value', 'foo')`, `const el = screen.getByText("foo"); expect(el).not.toHaveProperty('value', 'foo')`, `const el = screen.getByText("foo"); expect(el).${preferred}`, `const el = screen.getByText("foo"); expect(el).${negatedPreferred}`, diff --git a/src/createBannedAttributeRule.js b/src/createBannedAttributeRule.js index 0f4a0e6..8807aef 100644 --- a/src/createBannedAttributeRule.js +++ b/src/createBannedAttributeRule.js @@ -13,6 +13,7 @@ export default ({ preferred, negatedPreferred, attributes }) => (context) => { : negatedPreferred; const isBannedArg = (node) => + node.arguments.length && attributes.some((attr) => attr === node.arguments[0].value); //expect(el).not.toBeEnabled() => expect(el).toBeDisabled() @@ -42,6 +43,10 @@ export default ({ preferred, negatedPreferred, attributes }) => (context) => { "CallExpression[callee.property.name=/toBe(Truthy|Falsy)?|toEqual/][callee.object.callee.name='expect']"( node ) { + if (!node.callee.object.arguments.length) { + return; + } + const { arguments: [{ object, property, property: { name } = {} }], } = node.callee.object; @@ -77,11 +82,11 @@ export default ({ preferred, negatedPreferred, attributes }) => (context) => { "CallExpression[callee.property.name=/toHaveProperty|toHaveAttribute/][callee.object.property.name='not'][callee.object.object.callee.name='expect']"( node ) { - const arg = node.arguments[0].value; if (!isBannedArg(node)) { return; } + const arg = node.arguments[0].value; const correctFunction = getCorrectFunctionFor(node, true); const incorrectFunction = node.callee.property.name;