summaryrefslogtreecommitdiff
path: root/tools/eslint-rules/prefer-assert-methods.js
blob: 8204a0e791699d52f4c1754ddd188602446e4259 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
 * @fileoverview Prohibit the use of assert operators ( ===, !==, ==, != )
 */

'use strict';

const astSelector = 'ExpressionStatement[expression.type="CallExpression"]' +
                    '[expression.callee.name="assert"]' +
                    '[expression.arguments.0.type="BinaryExpression"]';

function parseError(method, op) {
  return `'assert.${method}' should be used instead of '${op}'`;
}

const preferredAssertMethod = {
  '===': 'strictEqual',
  '!==': 'notStrictEqual',
  '==': 'equal',
  '!=': 'notEqual',
};

module.exports = {
  meta: { fixable: 'code' },
  create(context) {
    return {
      [astSelector]: function(node) {
        const arg = node.expression.arguments[0];
        const assertMethod = preferredAssertMethod[arg.operator];
        if (assertMethod) {
          context.report({
            node,
            message: parseError(assertMethod, arg.operator),
            fix: (fixer) => {
              const sourceCode = context.getSourceCode();
              const left = sourceCode.getText(arg.left);
              const right = sourceCode.getText(arg.right);
              return fixer.replaceText(
                node,
                `assert.${assertMethod}(${left}, ${right});`,
              );
            },
          });
        }
      },
    };
  },
};