utils.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.getAccessorValue = exports.followTypeAssertionChain = exports.createRule = exports.TestCaseProperty = exports.TestCaseName = exports.ModifierName = exports.HookName = exports.EqualityMatcher = exports.DescribeProperty = exports.DescribeAlias = void 0;
  6. exports.getNodeName = getNodeName;
  7. exports.scopeHasLocalReference = exports.parseExpectCall = exports.isTestCaseCall = exports.isSupportedAccessor = exports.isStringNode = exports.isParsedEqualityMatcherCall = exports.isIdentifier = exports.isHook = exports.isFunction = exports.isExpectMember = exports.isExpectCall = exports.isDescribeCall = exports.hasOnlyOneArgument = exports.getTestCallExpressionsFromDeclaredVariables = exports.getStringValue = void 0;
  8. var _path = require("path");
  9. var _experimentalUtils = require("@typescript-eslint/experimental-utils");
  10. var _package = require("../../package.json");
  11. const REPO_URL = 'https://github.com/jest-community/eslint-plugin-jest';
  12. const createRule = _experimentalUtils.ESLintUtils.RuleCreator(name => {
  13. const ruleName = (0, _path.parse)(name).name;
  14. return `${REPO_URL}/blob/v${_package.version}/docs/rules/${ruleName}.md`;
  15. });
  16. exports.createRule = createRule;
  17. const isTypeCastExpression = node => node.type === _experimentalUtils.AST_NODE_TYPES.TSAsExpression || node.type === _experimentalUtils.AST_NODE_TYPES.TSTypeAssertion;
  18. const followTypeAssertionChain = expression => isTypeCastExpression(expression) ? followTypeAssertionChain(expression.expression) : expression;
  19. /**
  20. * A `Literal` with a `value` of type `string`.
  21. */
  22. exports.followTypeAssertionChain = followTypeAssertionChain;
  23. /**
  24. * Checks if the given `node` is a `StringLiteral`.
  25. *
  26. * If a `value` is provided & the `node` is a `StringLiteral`,
  27. * the `value` will be compared to that of the `StringLiteral`.
  28. *
  29. * @param {Node} node
  30. * @param {V} [value]
  31. *
  32. * @return {node is StringLiteral<V>}
  33. *
  34. * @template V
  35. */
  36. const isStringLiteral = (node, value) => node.type === _experimentalUtils.AST_NODE_TYPES.Literal && typeof node.value === 'string' && (value === undefined || node.value === value);
  37. /**
  38. * Checks if the given `node` is a `TemplateLiteral`.
  39. *
  40. * Complex `TemplateLiteral`s are not considered specific, and so will return `false`.
  41. *
  42. * If a `value` is provided & the `node` is a `TemplateLiteral`,
  43. * the `value` will be compared to that of the `TemplateLiteral`.
  44. *
  45. * @param {Node} node
  46. * @param {V} [value]
  47. *
  48. * @return {node is TemplateLiteral<V>}
  49. *
  50. * @template V
  51. */
  52. const isTemplateLiteral = (node, value) => node.type === _experimentalUtils.AST_NODE_TYPES.TemplateLiteral && node.quasis.length === 1 && ( // bail out if not simple
  53. value === undefined || node.quasis[0].value.raw === value);
  54. /**
  55. * Checks if the given `node` is a {@link StringNode}.
  56. *
  57. * @param {Node} node
  58. * @param {V} [specifics]
  59. *
  60. * @return {node is StringNode}
  61. *
  62. * @template V
  63. */
  64. const isStringNode = (node, specifics) => isStringLiteral(node, specifics) || isTemplateLiteral(node, specifics);
  65. /**
  66. * Gets the value of the given `StringNode`.
  67. *
  68. * If the `node` is a `TemplateLiteral`, the `raw` value is used;
  69. * otherwise, `value` is returned instead.
  70. *
  71. * @param {StringNode<S>} node
  72. *
  73. * @return {S}
  74. *
  75. * @template S
  76. */
  77. exports.isStringNode = isStringNode;
  78. const getStringValue = node => isTemplateLiteral(node) ? node.quasis[0].value.raw : node.value;
  79. /**
  80. * Represents a `MemberExpression` with a "known" `property`.
  81. */
  82. exports.getStringValue = getStringValue;
  83. /**
  84. * Guards that the given `call` has only one `argument`.
  85. *
  86. * @param {CallExpression} call
  87. *
  88. * @return {call is CallExpressionWithSingleArgument}
  89. */
  90. const hasOnlyOneArgument = call => call.arguments.length === 1;
  91. /**
  92. * An `Identifier` with a known `name` value - i.e `expect`.
  93. */
  94. exports.hasOnlyOneArgument = hasOnlyOneArgument;
  95. /**
  96. * Checks if the given `node` is an `Identifier`.
  97. *
  98. * If a `name` is provided, & the `node` is an `Identifier`,
  99. * the `name` will be compared to that of the `identifier`.
  100. *
  101. * @param {Node} node
  102. * @param {V} [name]
  103. *
  104. * @return {node is KnownIdentifier<Name>}
  105. *
  106. * @template V
  107. */
  108. const isIdentifier = (node, name) => node.type === _experimentalUtils.AST_NODE_TYPES.Identifier && (name === undefined || node.name === name);
  109. /**
  110. * Checks if the given `node` is a "supported accessor".
  111. *
  112. * This means that it's a node can be used to access properties,
  113. * and who's "value" can be statically determined.
  114. *
  115. * `MemberExpression` nodes most commonly contain accessors,
  116. * but it's possible for other nodes to contain them.
  117. *
  118. * If a `value` is provided & the `node` is an `AccessorNode`,
  119. * the `value` will be compared to that of the `AccessorNode`.
  120. *
  121. * Note that `value` here refers to the normalised value.
  122. * The property that holds the value is not always called `name`.
  123. *
  124. * @param {Node} node
  125. * @param {V} [value]
  126. *
  127. * @return {node is AccessorNode<V>}
  128. *
  129. * @template V
  130. */
  131. exports.isIdentifier = isIdentifier;
  132. const isSupportedAccessor = (node, value) => isIdentifier(node, value) || isStringNode(node, value);
  133. /**
  134. * Gets the value of the given `AccessorNode`,
  135. * account for the different node types.
  136. *
  137. * @param {AccessorNode<S>} accessor
  138. *
  139. * @return {S}
  140. *
  141. * @template S
  142. */
  143. exports.isSupportedAccessor = isSupportedAccessor;
  144. const getAccessorValue = accessor => accessor.type === _experimentalUtils.AST_NODE_TYPES.Identifier ? accessor.name : getStringValue(accessor);
  145. exports.getAccessorValue = getAccessorValue;
  146. /**
  147. * Checks if the given `node` is a valid `ExpectCall`.
  148. *
  149. * In order to be an `ExpectCall`, the `node` must:
  150. * * be a `CallExpression`,
  151. * * have an accessor named 'expect',
  152. * * have a `parent`.
  153. *
  154. * @param {Node} node
  155. *
  156. * @return {node is ExpectCall}
  157. */
  158. const isExpectCall = node => node.type === _experimentalUtils.AST_NODE_TYPES.CallExpression && isSupportedAccessor(node.callee, 'expect') && node.parent !== undefined;
  159. exports.isExpectCall = isExpectCall;
  160. const isExpectMember = (node, name) => node.type === _experimentalUtils.AST_NODE_TYPES.MemberExpression && isSupportedAccessor(node.property, name);
  161. /**
  162. * Represents all the jest matchers.
  163. */
  164. exports.isExpectMember = isExpectMember;
  165. let ModifierName;
  166. exports.ModifierName = ModifierName;
  167. (function (ModifierName) {
  168. ModifierName["not"] = "not";
  169. ModifierName["rejects"] = "rejects";
  170. ModifierName["resolves"] = "resolves";
  171. })(ModifierName || (exports.ModifierName = ModifierName = {}));
  172. let EqualityMatcher;
  173. exports.EqualityMatcher = EqualityMatcher;
  174. (function (EqualityMatcher) {
  175. EqualityMatcher["toBe"] = "toBe";
  176. EqualityMatcher["toEqual"] = "toEqual";
  177. EqualityMatcher["toStrictEqual"] = "toStrictEqual";
  178. })(EqualityMatcher || (exports.EqualityMatcher = EqualityMatcher = {}));
  179. const isParsedEqualityMatcherCall = (matcher, name) => (name ? matcher.name === name : EqualityMatcher.hasOwnProperty(matcher.name)) && matcher.arguments !== null && matcher.arguments.length === 1;
  180. /**
  181. * Represents a parsed expect matcher, such as `toBe`, `toContain`, and so on.
  182. */
  183. exports.isParsedEqualityMatcherCall = isParsedEqualityMatcherCall;
  184. const parseExpectMember = expectMember => ({
  185. name: getAccessorValue(expectMember.property),
  186. node: expectMember
  187. });
  188. const reparseAsMatcher = parsedMember => ({ ...parsedMember,
  189. /**
  190. * The arguments being passed to this `Matcher`, if any.
  191. *
  192. * If this matcher isn't called, this will be `null`.
  193. */
  194. arguments: parsedMember.node.parent.type === _experimentalUtils.AST_NODE_TYPES.CallExpression ? parsedMember.node.parent.arguments : null
  195. });
  196. /**
  197. * Re-parses the given `parsedMember` as a `ParsedExpectModifier`.
  198. *
  199. * If the given `parsedMember` does not have a `name` of a valid `Modifier`,
  200. * an exception will be thrown.
  201. *
  202. * @param {ParsedExpectMember<ModifierName>} parsedMember
  203. *
  204. * @return {ParsedExpectModifier}
  205. */
  206. const reparseMemberAsModifier = parsedMember => {
  207. if (isSpecificMember(parsedMember, ModifierName.not)) {
  208. return parsedMember;
  209. }
  210. /* istanbul ignore if */
  211. if (!isSpecificMember(parsedMember, ModifierName.resolves) && !isSpecificMember(parsedMember, ModifierName.rejects)) {
  212. // ts doesn't think that the ModifierName.not check is the direct inverse as the above two checks
  213. // todo: impossible at runtime, but can't be typed w/o negation support
  214. throw new Error(`modifier name must be either "${ModifierName.resolves}" or "${ModifierName.rejects}" (got "${parsedMember.name}")`);
  215. }
  216. const negation = isExpectMember(parsedMember.node.parent, ModifierName.not) ? parsedMember.node.parent : undefined;
  217. return { ...parsedMember,
  218. negation
  219. };
  220. };
  221. const isSpecificMember = (member, specific) => member.name === specific;
  222. /**
  223. * Checks if the given `ParsedExpectMember` should be re-parsed as an `ParsedExpectModifier`.
  224. *
  225. * @param {ParsedExpectMember} member
  226. *
  227. * @return {member is ParsedExpectMember<ModifierName>}
  228. */
  229. const shouldBeParsedExpectModifier = member => ModifierName.hasOwnProperty(member.name);
  230. const parseExpectCall = expect => {
  231. const expectation = {
  232. expect
  233. };
  234. if (!isExpectMember(expect.parent)) {
  235. return expectation;
  236. }
  237. const parsedMember = parseExpectMember(expect.parent);
  238. if (!shouldBeParsedExpectModifier(parsedMember)) {
  239. expectation.matcher = reparseAsMatcher(parsedMember);
  240. return expectation;
  241. }
  242. const modifier = expectation.modifier = reparseMemberAsModifier(parsedMember);
  243. const memberNode = modifier.negation || modifier.node;
  244. if (!isExpectMember(memberNode.parent)) {
  245. return expectation;
  246. }
  247. expectation.matcher = reparseAsMatcher(parseExpectMember(memberNode.parent));
  248. return expectation;
  249. };
  250. exports.parseExpectCall = parseExpectCall;
  251. let DescribeAlias;
  252. exports.DescribeAlias = DescribeAlias;
  253. (function (DescribeAlias) {
  254. DescribeAlias["describe"] = "describe";
  255. DescribeAlias["fdescribe"] = "fdescribe";
  256. DescribeAlias["xdescribe"] = "xdescribe";
  257. })(DescribeAlias || (exports.DescribeAlias = DescribeAlias = {}));
  258. let TestCaseName;
  259. exports.TestCaseName = TestCaseName;
  260. (function (TestCaseName) {
  261. TestCaseName["fit"] = "fit";
  262. TestCaseName["it"] = "it";
  263. TestCaseName["test"] = "test";
  264. TestCaseName["xit"] = "xit";
  265. TestCaseName["xtest"] = "xtest";
  266. })(TestCaseName || (exports.TestCaseName = TestCaseName = {}));
  267. let HookName;
  268. exports.HookName = HookName;
  269. (function (HookName) {
  270. HookName["beforeAll"] = "beforeAll";
  271. HookName["beforeEach"] = "beforeEach";
  272. HookName["afterAll"] = "afterAll";
  273. HookName["afterEach"] = "afterEach";
  274. })(HookName || (exports.HookName = HookName = {}));
  275. let DescribeProperty;
  276. exports.DescribeProperty = DescribeProperty;
  277. (function (DescribeProperty) {
  278. DescribeProperty["each"] = "each";
  279. DescribeProperty["only"] = "only";
  280. DescribeProperty["skip"] = "skip";
  281. })(DescribeProperty || (exports.DescribeProperty = DescribeProperty = {}));
  282. let TestCaseProperty;
  283. exports.TestCaseProperty = TestCaseProperty;
  284. (function (TestCaseProperty) {
  285. TestCaseProperty["each"] = "each";
  286. TestCaseProperty["concurrent"] = "concurrent";
  287. TestCaseProperty["only"] = "only";
  288. TestCaseProperty["skip"] = "skip";
  289. TestCaseProperty["todo"] = "todo";
  290. })(TestCaseProperty || (exports.TestCaseProperty = TestCaseProperty = {}));
  291. const joinNames = (a, b) => a && b ? `${a}.${b}` : null;
  292. function getNodeName(node) {
  293. if (isSupportedAccessor(node)) {
  294. return getAccessorValue(node);
  295. }
  296. switch (node.type) {
  297. case _experimentalUtils.AST_NODE_TYPES.TaggedTemplateExpression:
  298. return getNodeName(node.tag);
  299. case _experimentalUtils.AST_NODE_TYPES.MemberExpression:
  300. return joinNames(getNodeName(node.object), getNodeName(node.property));
  301. case _experimentalUtils.AST_NODE_TYPES.NewExpression:
  302. case _experimentalUtils.AST_NODE_TYPES.CallExpression:
  303. return getNodeName(node.callee);
  304. }
  305. return null;
  306. }
  307. const isFunction = node => node.type === _experimentalUtils.AST_NODE_TYPES.FunctionExpression || node.type === _experimentalUtils.AST_NODE_TYPES.ArrowFunctionExpression;
  308. exports.isFunction = isFunction;
  309. const isHook = node => node.callee.type === _experimentalUtils.AST_NODE_TYPES.Identifier && HookName.hasOwnProperty(node.callee.name);
  310. exports.isHook = isHook;
  311. const getTestCallExpressionsFromDeclaredVariables = declaredVariables => {
  312. return declaredVariables.reduce((acc, {
  313. references
  314. }) => acc.concat(references.map(({
  315. identifier
  316. }) => identifier.parent).filter(node => !!node && node.type === _experimentalUtils.AST_NODE_TYPES.CallExpression && isTestCaseCall(node))), []);
  317. };
  318. exports.getTestCallExpressionsFromDeclaredVariables = getTestCallExpressionsFromDeclaredVariables;
  319. const isTestCaseName = node => node.type === _experimentalUtils.AST_NODE_TYPES.Identifier && TestCaseName.hasOwnProperty(node.name);
  320. const isTestCaseProperty = node => isSupportedAccessor(node) && TestCaseProperty.hasOwnProperty(getAccessorValue(node));
  321. /**
  322. * Checks if the given `node` is a *call* to a test case function that would
  323. * result in tests being run by `jest`.
  324. *
  325. * Note that `.each()` does not count as a call in this context, as it will not
  326. * result in `jest` running any tests.
  327. *
  328. * @param {TSESTree.CallExpression} node
  329. *
  330. * @return {node is JestFunctionCallExpression<TestCaseName>}
  331. */
  332. const isTestCaseCall = node => {
  333. if (isTestCaseName(node.callee)) {
  334. return true;
  335. }
  336. const callee = node.callee.type === _experimentalUtils.AST_NODE_TYPES.TaggedTemplateExpression ? node.callee.tag : node.callee.type === _experimentalUtils.AST_NODE_TYPES.CallExpression ? node.callee.callee : node.callee;
  337. if (callee.type === _experimentalUtils.AST_NODE_TYPES.MemberExpression && isTestCaseProperty(callee.property)) {
  338. // if we're an `each()`, ensure we're the outer CallExpression (i.e `.each()()`)
  339. if (getAccessorValue(callee.property) === 'each' && node.callee.type !== _experimentalUtils.AST_NODE_TYPES.TaggedTemplateExpression && node.callee.type !== _experimentalUtils.AST_NODE_TYPES.CallExpression) {
  340. return false;
  341. }
  342. return callee.object.type === _experimentalUtils.AST_NODE_TYPES.MemberExpression ? isTestCaseName(callee.object.object) : isTestCaseName(callee.object);
  343. }
  344. return false;
  345. };
  346. exports.isTestCaseCall = isTestCaseCall;
  347. const isDescribeAlias = node => node.type === _experimentalUtils.AST_NODE_TYPES.Identifier && DescribeAlias.hasOwnProperty(node.name);
  348. const isDescribeProperty = node => isSupportedAccessor(node) && DescribeProperty.hasOwnProperty(getAccessorValue(node));
  349. /**
  350. * Checks if the given `node` is a *call* to a `describe` function that would
  351. * result in a `describe` block being created by `jest`.
  352. *
  353. * Note that `.each()` does not count as a call in this context, as it will not
  354. * result in `jest` creating any `describe` blocks.
  355. *
  356. * @param {TSESTree.CallExpression} node
  357. *
  358. * @return {node is JestFunctionCallExpression<TestCaseName>}
  359. */
  360. const isDescribeCall = node => {
  361. if (isDescribeAlias(node.callee)) {
  362. return true;
  363. }
  364. const callee = node.callee.type === _experimentalUtils.AST_NODE_TYPES.TaggedTemplateExpression ? node.callee.tag : node.callee.type === _experimentalUtils.AST_NODE_TYPES.CallExpression ? node.callee.callee : node.callee;
  365. if (callee.type === _experimentalUtils.AST_NODE_TYPES.MemberExpression && isDescribeProperty(callee.property)) {
  366. // if we're an `each()`, ensure we're the outer CallExpression (i.e `.each()()`)
  367. if (getAccessorValue(callee.property) === 'each' && node.callee.type !== _experimentalUtils.AST_NODE_TYPES.TaggedTemplateExpression && node.callee.type !== _experimentalUtils.AST_NODE_TYPES.CallExpression) {
  368. return false;
  369. }
  370. return callee.object.type === _experimentalUtils.AST_NODE_TYPES.MemberExpression ? isDescribeAlias(callee.object.object) : isDescribeAlias(callee.object);
  371. }
  372. return false;
  373. };
  374. exports.isDescribeCall = isDescribeCall;
  375. const collectReferences = scope => {
  376. const locals = new Set();
  377. const unresolved = new Set();
  378. let currentScope = scope;
  379. while (currentScope !== null) {
  380. for (const ref of currentScope.variables) {
  381. const isReferenceDefined = ref.defs.some(def => {
  382. return def.type !== 'ImplicitGlobalVariable';
  383. });
  384. if (isReferenceDefined) {
  385. locals.add(ref.name);
  386. }
  387. }
  388. for (const ref of currentScope.through) {
  389. unresolved.add(ref.identifier.name);
  390. }
  391. currentScope = currentScope.upper;
  392. }
  393. return {
  394. locals,
  395. unresolved
  396. };
  397. };
  398. const scopeHasLocalReference = (scope, referenceName) => {
  399. const references = collectReferences(scope);
  400. return (// referenceName was found as a local variable or function declaration.
  401. references.locals.has(referenceName) || // referenceName was not found as an unresolved reference,
  402. // meaning it is likely not an implicit global reference.
  403. !references.unresolved.has(referenceName)
  404. );
  405. };
  406. exports.scopeHasLocalReference = scopeHasLocalReference;