prefer-to-have-length.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. var _default = (0, _utils2.createRule)({
  9. name: __filename,
  10. meta: {
  11. docs: {
  12. category: 'Best Practices',
  13. description: 'Suggest using `toHaveLength()`',
  14. recommended: false
  15. },
  16. messages: {
  17. useToHaveLength: 'Use toHaveLength() instead'
  18. },
  19. fixable: 'code',
  20. type: 'suggestion',
  21. schema: []
  22. },
  23. defaultOptions: [],
  24. create(context) {
  25. return {
  26. CallExpression(node) {
  27. const jestFnCall = (0, _utils2.parseJestFnCall)(node, context);
  28. if ((jestFnCall === null || jestFnCall === void 0 ? void 0 : jestFnCall.type) !== 'expect') {
  29. return;
  30. }
  31. const {
  32. parent: expect
  33. } = jestFnCall.head.node;
  34. if ((expect === null || expect === void 0 ? void 0 : expect.type) !== _utils.AST_NODE_TYPES.CallExpression) {
  35. return;
  36. }
  37. const [argument] = expect.arguments;
  38. const {
  39. matcher
  40. } = jestFnCall;
  41. if (!_utils2.EqualityMatcher.hasOwnProperty((0, _utils2.getAccessorValue)(matcher)) || (argument === null || argument === void 0 ? void 0 : argument.type) !== _utils.AST_NODE_TYPES.MemberExpression || !(0, _utils2.isSupportedAccessor)(argument.property, 'length')) {
  42. return;
  43. }
  44. context.report({
  45. fix(fixer) {
  46. return [// remove the "length" property accessor
  47. fixer.removeRange([argument.property.range[0] - 1, argument.range[1]]), // replace the current matcher with "toHaveLength"
  48. fixer.replaceTextRange([matcher.parent.object.range[1], matcher.parent.range[1]], '.toHaveLength')];
  49. },
  50. messageId: 'useToHaveLength',
  51. node: matcher
  52. });
  53. }
  54. };
  55. }
  56. });
  57. exports.default = _default;