no-alias-methods.js 1.83 KB
Newer Older
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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
'use strict';

const { expectCase, getDocsUrl, method } = require('./util');

module.exports = {
  meta: {
    docs: {
      url: getDocsUrl(__filename),
    },
    fixable: 'code',
  },
  create(context) {
    // The Jest methods which have aliases. The canonical name is the first
    // index of each item.
    const methodNames = [
      ['toHaveBeenCalled', 'toBeCalled'],
      ['toHaveBeenCalledTimes', 'toBeCalledTimes'],
      ['toHaveBeenCalledWith', 'toBeCalledWith'],
      ['toHaveBeenLastCalledWith', 'lastCalledWith'],
      ['toHaveBeenNthCalledWith', 'nthCalledWith'],
      ['toHaveReturned', 'toReturn'],
      ['toHaveReturnedTimes', 'toReturnTimes'],
      ['toHaveReturnedWith', 'toReturnWith'],
      ['toHaveLastReturnedWith', 'lastReturnedWith'],
      ['toHaveNthReturnedWith', 'nthReturnedWith'],
      ['toThrow', 'toThrowError'],
    ];

    return {
      CallExpression(node) {
        if (!expectCase(node)) {
          return;
        }

        let targetNode = method(node);
        if (
          targetNode.name === 'resolves' ||
          targetNode.name === 'rejects' ||
          targetNode.name === 'not'
        ) {
          targetNode = method(node.parent);
        }

        if (!targetNode) {
          return;
        }

        // Check if the method used matches any of ours
        const methodItem = methodNames.find(
          item => item[1] === targetNode.name
        );

        if (methodItem) {
          context.report({
            message: `Replace {{ replace }}() with its canonical name of {{ canonical }}()`,
            data: {
              replace: methodItem[1],
              canonical: methodItem[0],
            },
            node: targetNode,
            fix(fixer) {
              return [fixer.replaceText(targetNode, methodItem[0])];
            },
          });
        }
      },
    };
  },
};