Skip to content
This repository has been archived by the owner on Aug 18, 2020. It is now read-only.

Commit

Permalink
chris feedback
Browse files Browse the repository at this point in the history
  • Loading branch information
cartogram committed Mar 26, 2019
1 parent 02eb059 commit 006611f
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 10 deletions.
4 changes: 2 additions & 2 deletions docs/rules/jest/no-if.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
# Prevent if statements in tests. (jest/no-if)
This rule prevents the use of if statements in tests.
This rule prevents the use of if statements in tests.

## Rule Details

If statments in tests is usually an indication that a test is attempting to cover too much. Each branch of code executing within an if statement will likely be better served by a test devoted to it.
If statments in tests is usually an indication that a test is attempting to cover too much, and are at risk of not testing the logic they intend to. Each branch of code executing within an if statement will likely be better served by a test devoted to it.

Examples of **incorrect** code for this rule:

Expand Down
24 changes: 16 additions & 8 deletions lib/rules/jest/no-if.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,24 +24,25 @@ module.exports = {
'Tests should not contain if statements.',
'This is usually an indication that you',
'are attempting to test too much at once',
'and may want to consider breaking the if',
'statement out into a separate test.',
'or not testing what you intend to.',
'Consider breaking the if statement out',
'into a separate test to resolve this error.',
].join(' '),
},
},

create(context) {
let inCallExpression = false;
let callExpressionDepth = 0;

return {
CallExpression(node) {
if (notTestFunction(node) || hasEmptyBody(node)) {
if (ignore(node)) {
return;
}
inCallExpression = true;
callExpressionDepth++;
},
IfStatement(node) {
if (!inCallExpression) {
if (callExpressionDepth === 0) {
return;
}

Expand All @@ -50,13 +51,20 @@ module.exports = {
node,
});
},
'CallExpression:exit': () => {
inCallExpression = false;
'CallExpression:exit': (node) => {
if (ignore(node)) {
return;
}
callExpressionDepth--;
},
};
},
};

function ignore(node) {
return notTestFunction(node) || hasEmptyBody(node);
}

function notTestFunction(node) {
const method = getMethodName(node);
return !matchTestFunctionName(method);
Expand Down
13 changes: 13 additions & 0 deletions tests/lib/rules/jest/no-if.js
Original file line number Diff line number Diff line change
Expand Up @@ -225,5 +225,18 @@ ruleTester.run('no-if', rule, {
},
],
},
{
code: `it('foo', () => {
callExpression()
if ('bar') {}
})
`,
parser,
errors: [
{
messageId: 'noIf',
},
],
},
],
});

0 comments on commit 006611f

Please sign in to comment.