|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +//------------------------------------------------------------------------------ |
| 4 | +// Rule Definition |
| 5 | +//------------------------------------------------------------------------------ |
| 6 | + |
| 7 | +/** @type {import('eslint').Rule.RuleModule} */ |
| 8 | +module.exports = { |
| 9 | + meta: { |
| 10 | + type: 'problem', |
| 11 | + docs: { |
| 12 | + description: 'disallow chain of `cy.get()` calls', |
| 13 | + recommended: false, |
| 14 | + url: 'https://github.com/cypress-io/eslint-plugin-cypress/blob/master/docs/rules/no-chained-get.md', |
| 15 | + }, |
| 16 | + fixable: null, |
| 17 | + schema: [], |
| 18 | + messages: { |
| 19 | + unexpected: 'Avoid chaining multiple cy.get() calls', |
| 20 | + }, |
| 21 | + }, |
| 22 | + |
| 23 | + create(context) { |
| 24 | + const isRootCypress = (node) => { |
| 25 | + if ( |
| 26 | + node.type !== 'CallExpression' || |
| 27 | + node.callee.type !== 'MemberExpression' |
| 28 | + ) { |
| 29 | + return false; |
| 30 | + } |
| 31 | + |
| 32 | + if ( |
| 33 | + node.callee.object.type === 'Identifier' && |
| 34 | + node.callee.object.name === 'cy' |
| 35 | + ) { |
| 36 | + return true; |
| 37 | + } |
| 38 | + |
| 39 | + return isRootCypress(node.callee.object); |
| 40 | + }; |
| 41 | + |
| 42 | + const hasChainedGet = (node) => { |
| 43 | + // Check if this node is a get() call |
| 44 | + const isGetCall = |
| 45 | + node.callee && |
| 46 | + node.callee.type === 'MemberExpression' && |
| 47 | + node.callee.property && |
| 48 | + node.callee.property.type === 'Identifier' && |
| 49 | + node.callee.property.name === 'get'; |
| 50 | + |
| 51 | + if (!isGetCall) { |
| 52 | + return false; |
| 53 | + } |
| 54 | + |
| 55 | + const obj = node.callee.object; |
| 56 | + |
| 57 | + if (obj.type === 'CallExpression') { |
| 58 | + const objCallee = obj.callee; |
| 59 | + |
| 60 | + if ( |
| 61 | + objCallee && |
| 62 | + objCallee.type === 'MemberExpression' && |
| 63 | + objCallee.property && |
| 64 | + objCallee.property.type === 'Identifier' && |
| 65 | + objCallee.property.name === 'get' |
| 66 | + ) { |
| 67 | + return true; |
| 68 | + } |
| 69 | + |
| 70 | + return hasChainedGet(obj); |
| 71 | + } |
| 72 | + |
| 73 | + return false; |
| 74 | + }; |
| 75 | + |
| 76 | + return { |
| 77 | + CallExpression(node) { |
| 78 | + if (isRootCypress(node) && hasChainedGet(node)) { |
| 79 | + context.report({ |
| 80 | + node, |
| 81 | + messageId: 'unexpected', |
| 82 | + }); |
| 83 | + } |
| 84 | + }, |
| 85 | + }; |
| 86 | + }, |
| 87 | +}; |
0 commit comments