prefer-spy-on.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _experimentalUtils = require("@typescript-eslint/experimental-utils");
  7. var _utils = require("./utils");
  8. const findNodeObject = node => {
  9. if ('object' in node) {
  10. return node.object;
  11. }
  12. if (node.callee.type === _experimentalUtils.AST_NODE_TYPES.MemberExpression) {
  13. return node.callee.object;
  14. }
  15. return null;
  16. };
  17. const getJestFnCall = node => {
  18. if (node.type !== _experimentalUtils.AST_NODE_TYPES.CallExpression && node.type !== _experimentalUtils.AST_NODE_TYPES.MemberExpression) {
  19. return null;
  20. }
  21. const obj = findNodeObject(node);
  22. if (!obj) {
  23. return null;
  24. }
  25. if (obj.type === _experimentalUtils.AST_NODE_TYPES.Identifier) {
  26. return node.type === _experimentalUtils.AST_NODE_TYPES.CallExpression && (0, _utils.getNodeName)(node.callee) === 'jest.fn' ? node : null;
  27. }
  28. return getJestFnCall(obj);
  29. };
  30. var _default = (0, _utils.createRule)({
  31. name: __filename,
  32. meta: {
  33. docs: {
  34. category: 'Best Practices',
  35. description: 'Suggest using `jest.spyOn()`',
  36. recommended: false
  37. },
  38. messages: {
  39. useJestSpyOn: 'Use jest.spyOn() instead.'
  40. },
  41. fixable: 'code',
  42. schema: [],
  43. type: 'suggestion'
  44. },
  45. defaultOptions: [],
  46. create(context) {
  47. return {
  48. AssignmentExpression(node) {
  49. const {
  50. left,
  51. right
  52. } = node;
  53. if (left.type !== _experimentalUtils.AST_NODE_TYPES.MemberExpression) return;
  54. const jestFnCall = getJestFnCall(right);
  55. if (!jestFnCall) return;
  56. context.report({
  57. node,
  58. messageId: 'useJestSpyOn',
  59. fix(fixer) {
  60. const leftPropQuote = left.property.type === _experimentalUtils.AST_NODE_TYPES.Identifier ? "'" : '';
  61. const [arg] = jestFnCall.arguments;
  62. const argSource = arg && context.getSourceCode().getText(arg);
  63. const mockImplementation = argSource ? `.mockImplementation(${argSource})` : '.mockImplementation()';
  64. return [fixer.insertTextBefore(left, `jest.spyOn(`), fixer.replaceTextRange([left.object.range[1], left.property.range[0]], `, ${leftPropQuote}`), fixer.replaceTextRange([left.property.range[1], jestFnCall.range[1]], `${leftPropQuote})${mockImplementation}`)];
  65. }
  66. });
  67. }
  68. };
  69. }
  70. });
  71. exports.default = _default;