Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ESlint: Handle modifiers on expect in valid-expect #3306

Merged
merged 1 commit into from
Apr 17, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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