no-done-callback.js 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  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. },
  37. defaultOptions: [],
  38. create(context) {
  39. return {
  40. CallExpression(node) {
  41. var _getNodeName$endsWith, _getNodeName;
  42. // done is the second argument for it.each, not the first
  43. 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;
  44. if (isJestEach && node.callee.type !== _experimentalUtils.AST_NODE_TYPES.TaggedTemplateExpression) {
  45. // isJestEach but not a TaggedTemplateExpression, so this must be
  46. // the `jest.each([])()` syntax which this rule doesn't support due
  47. // to its complexity (see jest-community/eslint-plugin-jest#710)
  48. return;
  49. }
  50. const callback = findCallbackArg(node, isJestEach);
  51. const callbackArgIndex = Number(isJestEach);
  52. if (!callback || !(0, _utils.isFunction)(callback) || callback.params.length !== 1 + callbackArgIndex) {
  53. return;
  54. }
  55. const argument = callback.params[callbackArgIndex];
  56. if (argument.type !== _experimentalUtils.AST_NODE_TYPES.Identifier) {
  57. context.report({
  58. node: argument,
  59. messageId: 'noDoneCallback'
  60. });
  61. return;
  62. }
  63. if (callback.async) {
  64. context.report({
  65. node: argument,
  66. messageId: 'useAwaitInsteadOfCallback'
  67. });
  68. return;
  69. }
  70. context.report({
  71. node: argument,
  72. messageId: 'noDoneCallback',
  73. suggest: [{
  74. messageId: 'suggestWrappingInPromise',
  75. data: {
  76. callback: argument.name
  77. },
  78. fix(fixer) {
  79. const {
  80. body
  81. } = callback;
  82. const sourceCode = context.getSourceCode();
  83. const firstBodyToken = sourceCode.getFirstToken(body);
  84. const lastBodyToken = sourceCode.getLastToken(body);
  85. const tokenBeforeArgument = sourceCode.getTokenBefore(argument);
  86. const tokenAfterArgument = sourceCode.getTokenAfter(argument);
  87. /* istanbul ignore if */
  88. if (!firstBodyToken || !lastBodyToken || !tokenBeforeArgument || !tokenAfterArgument) {
  89. 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`);
  90. }
  91. const argumentInParens = tokenBeforeArgument.value === '(' && tokenAfterArgument.value === ')';
  92. let argumentFix = fixer.replaceText(argument, '()');
  93. if (argumentInParens) {
  94. argumentFix = fixer.remove(argument);
  95. }
  96. let newCallback = argument.name;
  97. if (argumentInParens) {
  98. newCallback = `(${newCallback})`;
  99. }
  100. let beforeReplacement = `new Promise(${newCallback} => `;
  101. let afterReplacement = ')';
  102. let replaceBefore = true;
  103. if (body.type === _experimentalUtils.AST_NODE_TYPES.BlockStatement) {
  104. const keyword = 'return';
  105. beforeReplacement = `${keyword} ${beforeReplacement}{`;
  106. afterReplacement += '}';
  107. replaceBefore = false;
  108. }
  109. return [argumentFix, replaceBefore ? fixer.insertTextBefore(firstBodyToken, beforeReplacement) : fixer.insertTextAfter(firstBodyToken, beforeReplacement), fixer.insertTextAfter(lastBodyToken, afterReplacement)];
  110. }
  111. }]
  112. });
  113. }
  114. };
  115. }
  116. });
  117. exports.default = _default;