valid-expect.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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. /*
  9. * This implementation is ported from from eslint-plugin-jasmine.
  10. * MIT license, Tom Vincent.
  11. */
  12. /**
  13. * Async assertions might be called in Promise
  14. * methods like `Promise.x(expect1)` or `Promise.x([expect1, expect2])`.
  15. * If that's the case, Promise node have to be awaited or returned.
  16. *
  17. * @Returns CallExpressionNode
  18. */
  19. const getPromiseCallExpressionNode = node => {
  20. if (node.type === _utils.AST_NODE_TYPES.ArrayExpression && node.parent && node.parent.type === _utils.AST_NODE_TYPES.CallExpression) {
  21. node = node.parent;
  22. }
  23. if (node.type === _utils.AST_NODE_TYPES.CallExpression && node.callee.type === _utils.AST_NODE_TYPES.MemberExpression && (0, _utils2.isSupportedAccessor)(node.callee.object, 'Promise') && node.parent) {
  24. return node;
  25. }
  26. return null;
  27. };
  28. const findPromiseCallExpressionNode = node => {
  29. var _node$parent;
  30. return (_node$parent = node.parent) !== null && _node$parent !== void 0 && _node$parent.parent && [_utils.AST_NODE_TYPES.CallExpression, _utils.AST_NODE_TYPES.ArrayExpression].includes(node.parent.type) ? getPromiseCallExpressionNode(node.parent) : null;
  31. };
  32. const getParentIfThenified = node => {
  33. var _node$parent2;
  34. const grandParentNode = (_node$parent2 = node.parent) === null || _node$parent2 === void 0 ? void 0 : _node$parent2.parent;
  35. if (grandParentNode && grandParentNode.type === _utils.AST_NODE_TYPES.CallExpression && grandParentNode.callee.type === _utils.AST_NODE_TYPES.MemberExpression && (0, _utils2.isSupportedAccessor)(grandParentNode.callee.property) && ['then', 'catch'].includes((0, _utils2.getAccessorValue)(grandParentNode.callee.property)) && grandParentNode.parent) {
  36. // Just in case `then`s are chained look one above.
  37. return getParentIfThenified(grandParentNode);
  38. }
  39. return node;
  40. };
  41. const isAcceptableReturnNode = (node, allowReturn) => {
  42. if (allowReturn && node.type === _utils.AST_NODE_TYPES.ReturnStatement) {
  43. return true;
  44. }
  45. if (node.type === _utils.AST_NODE_TYPES.ConditionalExpression && node.parent) {
  46. return isAcceptableReturnNode(node.parent, allowReturn);
  47. }
  48. return [_utils.AST_NODE_TYPES.ArrowFunctionExpression, _utils.AST_NODE_TYPES.AwaitExpression].includes(node.type);
  49. };
  50. const promiseArrayExceptionKey = ({
  51. start,
  52. end
  53. }) => `${start.line}:${start.column}-${end.line}:${end.column}`;
  54. const defaultAsyncMatchers = ['toReject', 'toResolve'];
  55. var _default = (0, _utils2.createRule)({
  56. name: __filename,
  57. meta: {
  58. docs: {
  59. category: 'Best Practices',
  60. description: 'Enforce valid `expect()` usage',
  61. recommended: 'error'
  62. },
  63. messages: {
  64. tooManyArgs: 'Expect takes at most {{ amount }} argument{{ s }}.',
  65. notEnoughArgs: 'Expect requires at least {{ amount }} argument{{ s }}.',
  66. modifierUnknown: 'Expect has an unknown modifier.',
  67. matcherNotFound: 'Expect must have a corresponding matcher call.',
  68. matcherNotCalled: 'Matchers must be called to assert.',
  69. asyncMustBeAwaited: 'Async assertions must be awaited{{ orReturned }}.',
  70. promisesWithAsyncAssertionsMustBeAwaited: 'Promises which return async assertions must be awaited{{ orReturned }}.'
  71. },
  72. type: 'suggestion',
  73. schema: [{
  74. type: 'object',
  75. properties: {
  76. alwaysAwait: {
  77. type: 'boolean',
  78. default: false
  79. },
  80. asyncMatchers: {
  81. type: 'array',
  82. items: {
  83. type: 'string'
  84. }
  85. },
  86. minArgs: {
  87. type: 'number',
  88. minimum: 1
  89. },
  90. maxArgs: {
  91. type: 'number',
  92. minimum: 1
  93. }
  94. },
  95. additionalProperties: false
  96. }]
  97. },
  98. defaultOptions: [{
  99. alwaysAwait: false,
  100. asyncMatchers: defaultAsyncMatchers,
  101. minArgs: 1,
  102. maxArgs: 1
  103. }],
  104. create(context, [{
  105. alwaysAwait,
  106. asyncMatchers = defaultAsyncMatchers,
  107. minArgs = 1,
  108. maxArgs = 1
  109. }]) {
  110. // Context state
  111. const arrayExceptions = new Set();
  112. const pushPromiseArrayException = loc => arrayExceptions.add(promiseArrayExceptionKey(loc));
  113. /**
  114. * Promise method that accepts an array of promises,
  115. * (eg. Promise.all), will throw warnings for the each
  116. * unawaited or non-returned promise. To avoid throwing
  117. * multiple warnings, we check if there is a warning in
  118. * the given location.
  119. */
  120. const promiseArrayExceptionExists = loc => arrayExceptions.has(promiseArrayExceptionKey(loc));
  121. const findTopMostMemberExpression = node => {
  122. let topMostMemberExpression = node;
  123. let {
  124. parent
  125. } = node;
  126. while (parent) {
  127. if (parent.type !== _utils.AST_NODE_TYPES.MemberExpression) {
  128. break;
  129. }
  130. topMostMemberExpression = parent;
  131. parent = parent.parent;
  132. }
  133. return topMostMemberExpression;
  134. };
  135. return {
  136. CallExpression(node) {
  137. const jestFnCall = (0, _utils2.parseJestFnCallWithReason)(node, context);
  138. if (typeof jestFnCall === 'string') {
  139. var _node$parent3;
  140. const reportingNode = ((_node$parent3 = node.parent) === null || _node$parent3 === void 0 ? void 0 : _node$parent3.type) === _utils.AST_NODE_TYPES.MemberExpression ? findTopMostMemberExpression(node.parent).property : node;
  141. if (jestFnCall === 'matcher-not-found') {
  142. context.report({
  143. messageId: 'matcherNotFound',
  144. node: reportingNode
  145. });
  146. return;
  147. }
  148. if (jestFnCall === 'matcher-not-called') {
  149. context.report({
  150. messageId: (0, _utils2.isSupportedAccessor)(reportingNode) && _utils2.ModifierName.hasOwnProperty((0, _utils2.getAccessorValue)(reportingNode)) ? 'matcherNotFound' : 'matcherNotCalled',
  151. node: reportingNode
  152. });
  153. }
  154. if (jestFnCall === 'modifier-unknown') {
  155. context.report({
  156. messageId: 'modifierUnknown',
  157. node: reportingNode
  158. });
  159. return;
  160. }
  161. return;
  162. } else if ((jestFnCall === null || jestFnCall === void 0 ? void 0 : jestFnCall.type) !== 'expect') {
  163. return;
  164. }
  165. const {
  166. parent: expect
  167. } = jestFnCall.head.node;
  168. if ((expect === null || expect === void 0 ? void 0 : expect.type) !== _utils.AST_NODE_TYPES.CallExpression) {
  169. return;
  170. }
  171. if (expect.arguments.length < minArgs) {
  172. const expectLength = (0, _utils2.getAccessorValue)(jestFnCall.head.node).length;
  173. const loc = {
  174. start: {
  175. column: expect.loc.start.column + expectLength,
  176. line: expect.loc.start.line
  177. },
  178. end: {
  179. column: expect.loc.start.column + expectLength + 1,
  180. line: expect.loc.start.line
  181. }
  182. };
  183. context.report({
  184. messageId: 'notEnoughArgs',
  185. data: {
  186. amount: minArgs,
  187. s: minArgs === 1 ? '' : 's'
  188. },
  189. node: expect,
  190. loc
  191. });
  192. }
  193. if (expect.arguments.length > maxArgs) {
  194. const {
  195. start
  196. } = expect.arguments[maxArgs].loc;
  197. const {
  198. end
  199. } = expect.arguments[expect.arguments.length - 1].loc;
  200. const loc = {
  201. start,
  202. end: {
  203. column: end.column - 1,
  204. line: end.line
  205. }
  206. };
  207. context.report({
  208. messageId: 'tooManyArgs',
  209. data: {
  210. amount: maxArgs,
  211. s: maxArgs === 1 ? '' : 's'
  212. },
  213. node: expect,
  214. loc
  215. });
  216. }
  217. const {
  218. matcher
  219. } = jestFnCall;
  220. const parentNode = matcher.parent.parent;
  221. const shouldBeAwaited = jestFnCall.modifiers.some(nod => (0, _utils2.getAccessorValue)(nod) !== 'not') || asyncMatchers.includes((0, _utils2.getAccessorValue)(matcher));
  222. if (!(parentNode !== null && parentNode !== void 0 && parentNode.parent) || !shouldBeAwaited) {
  223. return;
  224. }
  225. /**
  226. * If parent node is an array expression, we'll report the warning,
  227. * for the array object, not for each individual assertion.
  228. */
  229. const isParentArrayExpression = parentNode.parent.type === _utils.AST_NODE_TYPES.ArrayExpression;
  230. const orReturned = alwaysAwait ? '' : ' or returned';
  231. /**
  232. * An async assertion can be chained with `then` or `catch` statements.
  233. * In that case our target CallExpression node is the one with
  234. * the last `then` or `catch` statement.
  235. */
  236. const targetNode = getParentIfThenified(parentNode);
  237. const finalNode = findPromiseCallExpressionNode(targetNode) || targetNode;
  238. if (finalNode.parent && // If node is not awaited or returned
  239. !isAcceptableReturnNode(finalNode.parent, !alwaysAwait) && // if we didn't warn user already
  240. !promiseArrayExceptionExists(finalNode.loc)) {
  241. context.report({
  242. loc: finalNode.loc,
  243. data: {
  244. orReturned
  245. },
  246. messageId: finalNode === targetNode ? 'asyncMustBeAwaited' : 'promisesWithAsyncAssertionsMustBeAwaited',
  247. node
  248. });
  249. if (isParentArrayExpression) {
  250. pushPromiseArrayException(finalNode.loc);
  251. }
  252. }
  253. }
  254. };
  255. }
  256. });
  257. exports.default = _default;