require-top-level-describe.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _utils = require("./utils");
  7. const messages = {
  8. tooManyDescribes: 'There should not be more than {{ max }} describe{{ s }} at the top level',
  9. unexpectedTestCase: 'All test cases must be wrapped in a describe block.',
  10. unexpectedHook: 'All hooks must be wrapped in a describe block.'
  11. };
  12. var _default = (0, _utils.createRule)({
  13. name: __filename,
  14. meta: {
  15. docs: {
  16. category: 'Best Practices',
  17. description: 'Require test cases and hooks to be inside a `describe` block',
  18. recommended: false
  19. },
  20. messages,
  21. type: 'suggestion',
  22. schema: [{
  23. type: 'object',
  24. properties: {
  25. maxNumberOfTopLevelDescribes: {
  26. type: 'number',
  27. minimum: 1
  28. }
  29. },
  30. additionalProperties: false
  31. }]
  32. },
  33. defaultOptions: [{}],
  34. create(context) {
  35. var _context$options$;
  36. const {
  37. maxNumberOfTopLevelDescribes = Infinity
  38. } = (_context$options$ = context.options[0]) !== null && _context$options$ !== void 0 ? _context$options$ : {};
  39. let numberOfTopLevelDescribeBlocks = 0;
  40. let numberOfDescribeBlocks = 0;
  41. return {
  42. CallExpression(node) {
  43. const jestFnCall = (0, _utils.parseJestFnCall)(node, context);
  44. if (!jestFnCall) {
  45. return;
  46. }
  47. if (jestFnCall.type === 'describe') {
  48. numberOfDescribeBlocks++;
  49. if (numberOfDescribeBlocks === 1) {
  50. numberOfTopLevelDescribeBlocks++;
  51. if (numberOfTopLevelDescribeBlocks > maxNumberOfTopLevelDescribes) {
  52. context.report({
  53. node,
  54. messageId: 'tooManyDescribes',
  55. data: {
  56. max: maxNumberOfTopLevelDescribes,
  57. s: maxNumberOfTopLevelDescribes === 1 ? '' : 's'
  58. }
  59. });
  60. }
  61. }
  62. return;
  63. }
  64. if (numberOfDescribeBlocks === 0) {
  65. if (jestFnCall.type === 'test') {
  66. context.report({
  67. node,
  68. messageId: 'unexpectedTestCase'
  69. });
  70. return;
  71. }
  72. if (jestFnCall.type === 'hook') {
  73. context.report({
  74. node,
  75. messageId: 'unexpectedHook'
  76. });
  77. return;
  78. }
  79. }
  80. },
  81. 'CallExpression:exit'(node) {
  82. if ((0, _utils.isTypeOfJestFnCall)(node, context, ['describe'])) {
  83. numberOfDescribeBlocks--;
  84. }
  85. }
  86. };
  87. }
  88. });
  89. exports.default = _default;