Skip to content

Commit

Permalink
ESlint: Handle modifiers on expect in valid-expect (jestjs#3306)
Browse files Browse the repository at this point in the history
  • Loading branch information
SimenB authored and skovhus committed Apr 29, 2017
1 parent 6c89c17 commit ff23a67
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ ruleTester.run('valid-expect', rules['valid-expect'], {
'expect(true).toBeDefined();',
'expect([1, 2, 3]).toEqual([1, 2, 3]);',
'expect(undefined).not.toBeDefined();',
'expect(Promise.resolve(2)).resolves.toBeDefined();',
'expect(Promise.reject(2)).rejects.toBeDefined();',
],

invalid: [
Expand Down Expand Up @@ -77,5 +79,21 @@ ruleTester.run('valid-expect', rules['valid-expect'], {
},
],
},
{
code: 'expect(true).not.toBeDefined;',
errors: [
{
message: '"toBeDefined" was not called.',
},
],
},
{
code: 'expect(true).nope.toBeDefined;',
errors: [
{
message: '"nope" is not a valid property of expect.',
},
],
},
],
});
36 changes: 29 additions & 7 deletions packages/eslint-plugin-jest/src/rules/valid-expect.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

import type {EslintContext, CallExpression} from './types';

const expectProperties = ['not', 'resolves', 'rejects'];

module.exports = (context: EslintContext) => {
return {
CallExpression(node: CallExpression) {
Expand All @@ -33,17 +35,37 @@ module.exports = (context: EslintContext) => {
});
}

// matcher was not called
// something was called on `expect()`
if (
node.parent &&
node.parent.type === 'MemberExpression' &&
node.parent.parent &&
node.parent.parent.type === 'ExpressionStatement'
node.parent.parent
) {
context.report({
message: `"${node.parent.property.name}" was not called.`,
node,
});
let propertyName = node.parent.property.name;
let grandParent = node.parent.parent;

// a property is accessed, get the next node
if (grandParent.type === 'MemberExpression') {
// a modifier is used, just get the next one
if (expectProperties.indexOf(propertyName) > -1) {
propertyName = grandParent.property.name;
grandParent = grandParent.parent;
} else {
// only a few properties are allowed
context.report({
message: `"${propertyName}" is not a valid property of expect.`,
node,
});
}
}

// matcher was not called
if (grandParent.type === 'ExpressionStatement') {
context.report({
message: `"${propertyName}" was not called.`,
node,
});
}
}
}
},
Expand Down

0 comments on commit ff23a67

Please sign in to comment.