diff --git a/lib/rules/prefer-explicit-assert.js b/lib/rules/prefer-explicit-assert.js index 60331c67..71451556 100644 --- a/lib/rules/prefer-explicit-assert.js +++ b/lib/rules/prefer-explicit-assert.js @@ -1,13 +1,13 @@ 'use strict'; -const { getDocsUrl, ALL_QUERIES_METHODS } = require('../utils'); +const { findParent, getDocsUrl, ALL_QUERIES_METHODS } = require('../utils'); const ALL_GET_BY_QUERIES = ALL_QUERIES_METHODS.map( queryMethod => `get${queryMethod}` ); const findCallExpressionParent = node => - node.type === 'CallExpression' ? node : findCallExpressionParent(node.parent); + findParent(node, node => node.type === 'CallExpression'); const isValidQuery = (node, customQueryNames = []) => ALL_GET_BY_QUERIES.includes(node.name) || @@ -19,11 +19,17 @@ const isDirectlyCalledByFunction = node => const isReturnedByArrowFunctionExpression = node => node.parent.type === 'ArrowFunctionExpression'; -const isDeclared = node => node.parent.type === 'VariableDeclarator'; +const isDeclared = node => + !!findParent(node, node => node.type === 'VariableDeclarator'); const isReturnedByReturnStatement = node => node.parent.type === 'ReturnStatement'; +const isInDestructuringStatement = node => + (node.parent.type === 'Property' && + node.parent.parent.type === 'ObjectPattern') || + node.parent.type === 'ArrayPattern'; + module.exports = { meta: { type: 'suggestion', @@ -63,6 +69,7 @@ module.exports = { if ( isValidQuery(node, customQueryNames) && + !isInDestructuringStatement(node) && !isDirectlyCalledByFunction(callExpressionNode) && !isReturnedByArrowFunctionExpression(callExpressionNode) && !isDeclared(callExpressionNode) && diff --git a/lib/utils.js b/lib/utils.js index bf8c2d17..0be515f8 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -48,7 +48,18 @@ const ALL_QUERIES_COMBINATIONS = [ ASYNC_QUERIES_COMBINATIONS, ]; +const findParent = (node, cb) => { + if (cb(node)) { + return node; + } else if (node.parent) { + return findParent(node.parent, cb); + } + + return null; +}; + module.exports = { + findParent, getDocsUrl, SYNC_QUERIES_VARIANTS, ASYNC_QUERIES_VARIANTS, diff --git a/tests/lib/rules/prefer-explicit-assert.js b/tests/lib/rules/prefer-explicit-assert.js index 9ca26f79..e523f0da 100644 --- a/tests/lib/rules/prefer-explicit-assert.js +++ b/tests/lib/rules/prefer-explicit-assert.js @@ -50,6 +50,21 @@ ruleTester.run('prefer-explicit-assert', rule, { { code: `getByIcon('foo')`, // custom `getBy` query not extended through options }, + { + code: `const { getByText } = render()`, + }, + { + code: `it('test', () => { const { getByText } = render() })`, + }, + { + code: `it('test', () => { const [ getByText ] = render() })`, + }, + { + code: `const a = [ getByText('foo') ]`, + }, + { + code: `const a = { foo: getByText('bar') }`, + }, ], invalid: [