valid-expect-in-promise.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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 isPromiseChainCall = node => {
  9. if (node.type === _experimentalUtils.AST_NODE_TYPES.CallExpression && node.callee.type === _experimentalUtils.AST_NODE_TYPES.MemberExpression && (0, _utils.isSupportedAccessor)(node.callee.property)) {
  10. // promise methods should have at least 1 argument
  11. if (node.arguments.length === 0) {
  12. return false;
  13. }
  14. switch ((0, _utils.getAccessorValue)(node.callee.property)) {
  15. case 'then':
  16. return node.arguments.length < 3;
  17. case 'catch':
  18. case 'finally':
  19. return node.arguments.length < 2;
  20. }
  21. }
  22. return false;
  23. };
  24. const findTopMostCallExpression = node => {
  25. let topMostCallExpression = node;
  26. let {
  27. parent
  28. } = node;
  29. while (parent) {
  30. if (parent.type === _experimentalUtils.AST_NODE_TYPES.CallExpression) {
  31. topMostCallExpression = parent;
  32. parent = parent.parent;
  33. continue;
  34. }
  35. if (parent.type !== _experimentalUtils.AST_NODE_TYPES.MemberExpression) {
  36. break;
  37. }
  38. parent = parent.parent;
  39. }
  40. return topMostCallExpression;
  41. };
  42. const isTestCaseCallWithCallbackArg = node => {
  43. if (!(0, _utils.isTestCaseCall)(node)) {
  44. return false;
  45. }
  46. const isJestEach = (0, _utils.getNodeName)(node).endsWith('.each');
  47. if (isJestEach && node.callee.type !== _experimentalUtils.AST_NODE_TYPES.TaggedTemplateExpression) {
  48. // isJestEach but not a TaggedTemplateExpression, so this must be
  49. // the `jest.each([])()` syntax which this rule doesn't support due
  50. // to its complexity (see jest-community/eslint-plugin-jest#710)
  51. // so we return true to trigger bailout
  52. return true;
  53. }
  54. if (isJestEach || node.arguments.length >= 2) {
  55. const [, callback] = node.arguments;
  56. const callbackArgIndex = Number(isJestEach);
  57. return callback && (0, _utils.isFunction)(callback) && callback.params.length === 1 + callbackArgIndex;
  58. }
  59. return false;
  60. };
  61. const isPromiseMethodThatUsesValue = (node, identifier) => {
  62. const {
  63. name
  64. } = identifier;
  65. if (node.argument === null) {
  66. return false;
  67. }
  68. if (node.argument.type === _experimentalUtils.AST_NODE_TYPES.CallExpression && node.argument.arguments.length > 0) {
  69. const nodeName = (0, _utils.getNodeName)(node.argument);
  70. if (['Promise.all', 'Promise.allSettled'].includes(nodeName)) {
  71. const [firstArg] = node.argument.arguments;
  72. if (firstArg.type === _experimentalUtils.AST_NODE_TYPES.ArrayExpression && firstArg.elements.some(nod => (0, _utils.isIdentifier)(nod, name))) {
  73. return true;
  74. }
  75. }
  76. if (['Promise.resolve', 'Promise.reject'].includes(nodeName) && node.argument.arguments.length === 1) {
  77. return (0, _utils.isIdentifier)(node.argument.arguments[0], name);
  78. }
  79. }
  80. return (0, _utils.isIdentifier)(node.argument, name);
  81. };
  82. /**
  83. * Attempts to determine if the runtime value represented by the given `identifier`
  84. * is `await`ed within the given array of elements
  85. */
  86. const isValueAwaitedInElements = (name, elements) => {
  87. for (const element of elements) {
  88. if (element.type === _experimentalUtils.AST_NODE_TYPES.AwaitExpression && (0, _utils.isIdentifier)(element.argument, name)) {
  89. return true;
  90. }
  91. if (element.type === _experimentalUtils.AST_NODE_TYPES.ArrayExpression && isValueAwaitedInElements(name, element.elements)) {
  92. return true;
  93. }
  94. }
  95. return false;
  96. };
  97. /**
  98. * Attempts to determine if the runtime value represented by the given `identifier`
  99. * is `await`ed as an argument along the given call expression
  100. */
  101. const isValueAwaitedInArguments = (name, call) => {
  102. let node = call;
  103. while (node) {
  104. if (node.type === _experimentalUtils.AST_NODE_TYPES.CallExpression) {
  105. if (isValueAwaitedInElements(name, node.arguments)) {
  106. return true;
  107. }
  108. node = node.callee;
  109. }
  110. if (node.type !== _experimentalUtils.AST_NODE_TYPES.MemberExpression) {
  111. break;
  112. }
  113. node = node.object;
  114. }
  115. return false;
  116. };
  117. const getLeftMostCallExpression = call => {
  118. let leftMostCallExpression = call;
  119. let node = call;
  120. while (node) {
  121. if (node.type === _experimentalUtils.AST_NODE_TYPES.CallExpression) {
  122. leftMostCallExpression = node;
  123. node = node.callee;
  124. }
  125. if (node.type !== _experimentalUtils.AST_NODE_TYPES.MemberExpression) {
  126. break;
  127. }
  128. node = node.object;
  129. }
  130. return leftMostCallExpression;
  131. };
  132. /**
  133. * Attempts to determine if the runtime value represented by the given `identifier`
  134. * is `await`ed or `return`ed within the given `body` of statements
  135. */
  136. const isValueAwaitedOrReturned = (identifier, body) => {
  137. const {
  138. name
  139. } = identifier;
  140. for (const node of body) {
  141. // skip all nodes that are before this identifier, because they'd probably
  142. // be affecting a different runtime value (e.g. due to reassignment)
  143. if (node.range[0] <= identifier.range[0]) {
  144. continue;
  145. }
  146. if (node.type === _experimentalUtils.AST_NODE_TYPES.ReturnStatement) {
  147. return isPromiseMethodThatUsesValue(node, identifier);
  148. }
  149. if (node.type === _experimentalUtils.AST_NODE_TYPES.ExpressionStatement) {
  150. // it's possible that we're awaiting the value as an argument
  151. if (node.expression.type === _experimentalUtils.AST_NODE_TYPES.CallExpression) {
  152. if (isValueAwaitedInArguments(name, node.expression)) {
  153. return true;
  154. }
  155. const leftMostCall = getLeftMostCallExpression(node.expression);
  156. if ((0, _utils.isExpectCall)(leftMostCall) && leftMostCall.arguments.length > 0 && (0, _utils.isIdentifier)(leftMostCall.arguments[0], name)) {
  157. const {
  158. modifier
  159. } = (0, _utils.parseExpectCall)(leftMostCall);
  160. if ((modifier === null || modifier === void 0 ? void 0 : modifier.name) === _utils.ModifierName.resolves || (modifier === null || modifier === void 0 ? void 0 : modifier.name) === _utils.ModifierName.rejects) {
  161. return true;
  162. }
  163. }
  164. }
  165. if (node.expression.type === _experimentalUtils.AST_NODE_TYPES.AwaitExpression && isPromiseMethodThatUsesValue(node.expression, identifier)) {
  166. return true;
  167. } // (re)assignment changes the runtime value, so if we've not found an
  168. // await or return already we act as if we've reached the end of the body
  169. if (node.expression.type === _experimentalUtils.AST_NODE_TYPES.AssignmentExpression) {
  170. var _getNodeName;
  171. // unless we're assigning to the same identifier, in which case
  172. // we might be chaining off the existing promise value
  173. if ((0, _utils.isIdentifier)(node.expression.left, name) && (_getNodeName = (0, _utils.getNodeName)(node.expression.right)) !== null && _getNodeName !== void 0 && _getNodeName.startsWith(`${name}.`) && isPromiseChainCall(node.expression.right)) {
  174. continue;
  175. }
  176. break;
  177. }
  178. }
  179. if (node.type === _experimentalUtils.AST_NODE_TYPES.BlockStatement && isValueAwaitedOrReturned(identifier, node.body)) {
  180. return true;
  181. }
  182. }
  183. return false;
  184. };
  185. const findFirstBlockBodyUp = node => {
  186. let parent = node;
  187. while (parent) {
  188. if (parent.type === _experimentalUtils.AST_NODE_TYPES.BlockStatement) {
  189. return parent.body;
  190. }
  191. parent = parent.parent;
  192. }
  193. /* istanbul ignore next */
  194. throw new Error(`Could not find BlockStatement - please file a github issue at https://github.com/jest-community/eslint-plugin-jest`);
  195. };
  196. const isDirectlyWithinTestCaseCall = node => {
  197. let parent = node;
  198. while (parent) {
  199. if ((0, _utils.isFunction)(parent)) {
  200. var _parent;
  201. parent = parent.parent;
  202. return !!(((_parent = parent) === null || _parent === void 0 ? void 0 : _parent.type) === _experimentalUtils.AST_NODE_TYPES.CallExpression && (0, _utils.isTestCaseCall)(parent));
  203. }
  204. parent = parent.parent;
  205. }
  206. return false;
  207. };
  208. const isVariableAwaitedOrReturned = variable => {
  209. const body = findFirstBlockBodyUp(variable); // it's pretty much impossible for us to track destructuring assignments,
  210. // so we return true to bailout gracefully
  211. if (!(0, _utils.isIdentifier)(variable.id)) {
  212. return true;
  213. }
  214. return isValueAwaitedOrReturned(variable.id, body);
  215. };
  216. var _default = (0, _utils.createRule)({
  217. name: __filename,
  218. meta: {
  219. docs: {
  220. category: 'Best Practices',
  221. description: 'Ensure promises that have expectations in their chain are valid',
  222. recommended: 'error'
  223. },
  224. messages: {
  225. expectInFloatingPromise: "This promise should either be returned or awaited to ensure the expects in it's chain are called"
  226. },
  227. type: 'suggestion',
  228. schema: []
  229. },
  230. defaultOptions: [],
  231. create(context) {
  232. let inTestCaseWithDoneCallback = false; // an array of booleans representing each promise chain we enter, with the
  233. // boolean value representing if we think a given chain contains an expect
  234. // in it's body.
  235. //
  236. // since we only care about the inner-most chain, we represent the state in
  237. // reverse with the inner-most being the first item, as that makes it
  238. // slightly less code to assign to by not needing to know the length
  239. const chains = [];
  240. return {
  241. CallExpression(node) {
  242. // there are too many ways that the done argument could be used with
  243. // promises that contain expect that would make the promise safe for us
  244. if (isTestCaseCallWithCallbackArg(node)) {
  245. inTestCaseWithDoneCallback = true;
  246. return;
  247. } // if this call expression is a promise chain, add it to the stack with
  248. // value of "false", as we assume there are no expect calls initially
  249. if (isPromiseChainCall(node)) {
  250. chains.unshift(false);
  251. return;
  252. } // if we're within a promise chain, and this call expression looks like
  253. // an expect call, mark the deepest chain as having an expect call
  254. if (chains.length > 0 && (0, _utils.isExpectCall)(node)) {
  255. chains[0] = true;
  256. }
  257. },
  258. 'CallExpression:exit'(node) {
  259. // there are too many ways that the "done" argument could be used to
  260. // make promises containing expects safe in a test for us to be able to
  261. // accurately check, so we just bail out completely if it's present
  262. if (inTestCaseWithDoneCallback) {
  263. if ((0, _utils.isTestCaseCall)(node)) {
  264. inTestCaseWithDoneCallback = false;
  265. }
  266. return;
  267. }
  268. if (!isPromiseChainCall(node)) {
  269. return;
  270. } // since we're exiting this call expression (which is a promise chain)
  271. // we remove it from the stack of chains, since we're unwinding
  272. const hasExpectCall = chains.shift(); // if the promise chain we're exiting doesn't contain an expect,
  273. // then we don't need to check it for anything
  274. if (!hasExpectCall) {
  275. return;
  276. }
  277. const {
  278. parent
  279. } = findTopMostCallExpression(node); // if we don't have a parent (which is technically impossible at runtime)
  280. // or our parent is not directly within the test case, we stop checking
  281. // because we're most likely in the body of a function being defined
  282. // within the test, which we can't track
  283. if (!parent || !isDirectlyWithinTestCaseCall(parent)) {
  284. return;
  285. }
  286. switch (parent.type) {
  287. case _experimentalUtils.AST_NODE_TYPES.VariableDeclarator:
  288. {
  289. if (isVariableAwaitedOrReturned(parent)) {
  290. return;
  291. }
  292. break;
  293. }
  294. case _experimentalUtils.AST_NODE_TYPES.AssignmentExpression:
  295. {
  296. if (parent.left.type === _experimentalUtils.AST_NODE_TYPES.Identifier && isValueAwaitedOrReturned(parent.left, findFirstBlockBodyUp(parent))) {
  297. return;
  298. }
  299. break;
  300. }
  301. case _experimentalUtils.AST_NODE_TYPES.ExpressionStatement:
  302. break;
  303. case _experimentalUtils.AST_NODE_TYPES.ReturnStatement:
  304. case _experimentalUtils.AST_NODE_TYPES.AwaitExpression:
  305. default:
  306. return;
  307. }
  308. context.report({
  309. messageId: 'expectInFloatingPromise',
  310. node: parent
  311. });
  312. }
  313. };
  314. }
  315. });
  316. exports.default = _default;