valid-expect.js 9.0 KB

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