prefer-presence-queries.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.RULE_NAME = void 0;
  4. var experimental_utils_1 = require("@typescript-eslint/experimental-utils");
  5. var utils_1 = require("../utils");
  6. var node_utils_1 = require("../node-utils");
  7. exports.RULE_NAME = 'prefer-presence-queries';
  8. var QUERIES_REGEXP = new RegExp("^(get|query)(All)?(" + utils_1.ALL_QUERIES_METHODS.join('|') + ")$");
  9. function isThrowingQuery(node) {
  10. return node.name.startsWith('get');
  11. }
  12. exports.default = experimental_utils_1.ESLintUtils.RuleCreator(utils_1.getDocsUrl)({
  13. name: exports.RULE_NAME,
  14. meta: {
  15. docs: {
  16. category: 'Best Practices',
  17. description: 'Ensure appropriate get*/query* queries are used with their respective matchers',
  18. recommended: 'error',
  19. },
  20. messages: {
  21. presenceQuery: 'Use `getBy*` queries rather than `queryBy*` for checking element is present',
  22. absenceQuery: 'Use `queryBy*` queries rather than `getBy*` for checking element is NOT present',
  23. expectQueryBy: 'Use `getBy*` only when checking elements are present, otherwise use `queryBy*`',
  24. },
  25. schema: [],
  26. type: 'suggestion',
  27. fixable: null,
  28. },
  29. defaultOptions: [],
  30. create: function (context) {
  31. var _a;
  32. return _a = {},
  33. _a["CallExpression Identifier[name=" + QUERIES_REGEXP + "]"] = function (node) {
  34. var expectCallNode = node_utils_1.findClosestCallNode(node, 'expect');
  35. if (expectCallNode && node_utils_1.isMemberExpression(expectCallNode.parent)) {
  36. var expectStatement = expectCallNode.parent;
  37. var property = expectStatement.property;
  38. var matcher = property.name;
  39. var isNegatedMatcher = false;
  40. if (matcher === 'not' &&
  41. node_utils_1.isMemberExpression(expectStatement.parent) &&
  42. node_utils_1.isIdentifier(expectStatement.parent.property)) {
  43. isNegatedMatcher = true;
  44. matcher = expectStatement.parent.property.name;
  45. }
  46. var validMatchers = isThrowingQuery(node)
  47. ? utils_1.PRESENCE_MATCHERS
  48. : utils_1.ABSENCE_MATCHERS;
  49. var invalidMatchers = isThrowingQuery(node)
  50. ? utils_1.ABSENCE_MATCHERS
  51. : utils_1.PRESENCE_MATCHERS;
  52. var messageId = isThrowingQuery(node)
  53. ? 'absenceQuery'
  54. : 'presenceQuery';
  55. if ((!isNegatedMatcher && invalidMatchers.includes(matcher)) ||
  56. (isNegatedMatcher && validMatchers.includes(matcher))) {
  57. return context.report({
  58. node: node,
  59. messageId: messageId,
  60. });
  61. }
  62. }
  63. },
  64. _a;
  65. },
  66. });