utils.js 17 KB

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