no-done-callback.js 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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 findCallbackArg = (node, isJestEach) => {
  9. if (isJestEach) {
  10. return node.arguments[1];
  11. }
  12. if ((0, _utils.isHook)(node) && node.arguments.length >= 1) {
  13. return node.arguments[0];
  14. }
  15. if ((0, _utils.isTestCaseCall)(node) && node.arguments.length >= 2) {
  16. return node.arguments[1];
  17. }
  18. return null;
  19. };
  20. var _default = (0, _utils.createRule)({
  21. name: __filename,
  22. meta: {
  23. docs: {
  24. category: 'Best Practices',
  25. description: 'Avoid using a callback in asynchronous tests and hooks',
  26. recommended: 'error',
  27. suggestion: true
  28. },
  29. messages: {
  30. noDoneCallback: 'Return a Promise instead of relying on callback parameter',
  31. suggestWrappingInPromise: 'Wrap in `new Promise({{ callback }} => ...`',
  32. useAwaitInsteadOfCallback: 'Use await instead of callback in async functions'
  33. },
  34. schema: [],
  35. type: 'suggestion',
  36. hasSuggestions: true
  37. },
  38. defaultOptions: [],
  39. create(context) {
  40. return {
  41. CallExpression(node) {
  42. var _getNodeName$endsWith, _getNodeName;
  43. // done is the second argument for it.each, not the first
  44. const isJestEach = (_getNodeName$endsWith = (_getNodeName = (0, _utils.getNodeName)(node.callee)) === null || _getNodeName === void 0 ? void 0 : _getNodeName.endsWith('.each')) !== null && _getNodeName$endsWith !== void 0 ? _getNodeName$endsWith : false;
  45. if (isJestEach && node.callee.type !== _experimentalUtils.AST_NODE_TYPES.TaggedTemplateExpression) {
  46. // isJestEach but not a TaggedTemplateExpression, so this must be
  47. // the `jest.each([])()` syntax which this rule doesn't support due
  48. // to its complexity (see jest-community/eslint-plugin-jest#710)
  49. return;
  50. }
  51. const callback = findCallbackArg(node, isJestEach);
  52. const callbackArgIndex = Number(isJestEach);
  53. if (!callback || !(0, _utils.isFunction)(callback) || callback.params.length !== 1 + callbackArgIndex) {
  54. return;
  55. }
  56. const argument = callback.params[callbackArgIndex];
  57. if (argument.type !== _experimentalUtils.AST_NODE_TYPES.Identifier) {
  58. context.report({
  59. node: argument,
  60. messageId: 'noDoneCallback'
  61. });
  62. return;
  63. }
  64. if (callback.async) {
  65. context.report({
  66. node: argument,
  67. messageId: 'useAwaitInsteadOfCallback'
  68. });
  69. return;
  70. }
  71. context.report({
  72. node: argument,
  73. messageId: 'noDoneCallback',
  74. suggest: [{
  75. messageId: 'suggestWrappingInPromise',
  76. data: {
  77. callback: argument.name
  78. },
  79. fix(fixer) {
  80. const {
  81. body
  82. } = callback;
  83. const sourceCode = context.getSourceCode();
  84. const firstBodyToken = sourceCode.getFirstToken(body);
  85. const lastBodyToken = sourceCode.getLastToken(body);
  86. const tokenBeforeArgument = sourceCode.getTokenBefore(argument);
  87. const tokenAfterArgument = sourceCode.getTokenAfter(argument);
  88. /* istanbul ignore if */
  89. if (!firstBodyToken || !lastBodyToken || !tokenBeforeArgument || !tokenAfterArgument) {
  90. throw new Error(`Unexpected null when attempting to fix ${context.getFilename()} - please file a github issue at https://github.com/jest-community/eslint-plugin-jest`);
  91. }
  92. const argumentInParens = tokenBeforeArgument.value === '(' && tokenAfterArgument.value === ')';
  93. let argumentFix = fixer.replaceText(argument, '()');
  94. if (argumentInParens) {
  95. argumentFix = fixer.remove(argument);
  96. }
  97. let newCallback = argument.name;
  98. if (argumentInParens) {
  99. newCallback = `(${newCallback})`;
  100. }
  101. let beforeReplacement = `new Promise(${newCallback} => `;
  102. let afterReplacement = ')';
  103. let replaceBefore = true;
  104. if (body.type === _experimentalUtils.AST_NODE_TYPES.BlockStatement) {
  105. const keyword = 'return';
  106. beforeReplacement = `${keyword} ${beforeReplacement}{`;
  107. afterReplacement += '}';
  108. replaceBefore = false;
  109. }
  110. return [argumentFix, replaceBefore ? fixer.insertTextBefore(firstBodyToken, beforeReplacement) : fixer.insertTextAfter(firstBodyToken, beforeReplacement), fixer.insertTextAfter(lastBodyToken, afterReplacement)];
  111. }
  112. }]
  113. });
  114. }
  115. };
  116. }
  117. });
  118. exports.default = _default;