no-done-callback.js 4.9 KB

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