Skip to content

Commit

Permalink
fix(require-tothrow-message): cover more cases (#161)
Browse files Browse the repository at this point in the history
  • Loading branch information
garyking authored and SimenB committed Sep 30, 2018
1 parent ee2647e commit f2d2dbe
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 35 deletions.
32 changes: 0 additions & 32 deletions rules/__tests__/require-tothrow-message.js

This file was deleted.

52 changes: 52 additions & 0 deletions rules/__tests__/require-tothrow-message.test.js
@@ -0,0 +1,52 @@
'use strict';

const RuleTester = require('eslint').RuleTester;
const rule = require('../require-tothrow-message');

const ruleTester = new RuleTester({
parserOptions: {
ecmaVersion: 6,
},
});

ruleTester.run('require-tothrow-message', rule, {
valid: [
// String
"expect(() => { throw new Error('a'); }).toThrow('a');",
"expect(() => { throw new Error('a'); }).toThrowError('a');",

// Template literal
"const a = 'a'; expect(() => { throw new Error('a'); }).toThrow(`${a}`);",

// Regex
"expect(() => { throw new Error('a'); }).toThrow(/^a$/);",

// Function
"expect(() => { throw new Error('a'); })" +
".toThrow((() => { return 'a'; })());",

// Allow no message for `not`.
"expect(() => { throw new Error('a'); }).not.toThrow();",
],

invalid: [
// Empty toThrow
{
code: "expect(() => { throw new Error('a'); }).toThrow();",
errors: [
{ message: 'Add an error message to toThrow()', column: 41, line: 1 },
],
},
// Empty toThrowError
{
code: "expect(() => { throw new Error('a'); }).toThrowError();",
errors: [
{
message: 'Add an error message to toThrowError()',
column: 41,
line: 1,
},
],
},
],
});
13 changes: 10 additions & 3 deletions rules/require-tothrow-message.js
@@ -1,6 +1,9 @@
'use strict';

const argument = require('./util').argument;
const expectCase = require('./util').expectCase;
const getDocsUrl = require('./util').getDocsUrl;
const method = require('./util').method;

module.exports = {
meta: {
Expand All @@ -11,19 +14,23 @@ module.exports = {
create(context) {
return {
CallExpression(node) {
const propertyName = node.callee.property && node.callee.property.name;
if (!expectCase(node)) {
return;
}

const propertyName = method(node) && method(node).name;

// Look for `toThrow` calls with no arguments.
if (
['toThrow', 'toThrowError'].indexOf(propertyName) > -1 &&
!(node.arguments[0] && node.arguments[0].type === 'Literal')
!argument(node)
) {
context.report({
message: `Add an error message to {{ propertyName }}()`,
data: {
propertyName,
},
node: node.callee.property,
node: method(node),
});
}
},
Expand Down

0 comments on commit f2d2dbe

Please sign in to comment.