no-conditional-expect.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _experimentalUtils = require("@typescript-eslint/experimental-utils");
  7. var _utils = require("./utils");
  8. const isCatchCall = node => node.callee.type === _experimentalUtils.AST_NODE_TYPES.MemberExpression && (0, _utils.isSupportedAccessor)(node.callee.property, 'catch');
  9. var _default = (0, _utils.createRule)({
  10. name: __filename,
  11. meta: {
  12. docs: {
  13. description: 'Prevent calling `expect` conditionally',
  14. category: 'Best Practices',
  15. recommended: 'error'
  16. },
  17. messages: {
  18. conditionalExpect: 'Avoid calling `expect` conditionally`'
  19. },
  20. type: 'problem',
  21. schema: []
  22. },
  23. defaultOptions: [],
  24. create(context) {
  25. let conditionalDepth = 0;
  26. let inTestCase = false;
  27. let inPromiseCatch = false;
  28. const increaseConditionalDepth = () => inTestCase && conditionalDepth++;
  29. const decreaseConditionalDepth = () => inTestCase && conditionalDepth--;
  30. return {
  31. FunctionDeclaration(node) {
  32. const declaredVariables = context.getDeclaredVariables(node);
  33. const testCallExpressions = (0, _utils.getTestCallExpressionsFromDeclaredVariables)(declaredVariables);
  34. if (testCallExpressions.length > 0) {
  35. inTestCase = true;
  36. }
  37. },
  38. CallExpression(node) {
  39. if ((0, _utils.isTestCaseCall)(node)) {
  40. inTestCase = true;
  41. }
  42. if (isCatchCall(node)) {
  43. inPromiseCatch = true;
  44. }
  45. if (inTestCase && (0, _utils.isExpectCall)(node) && conditionalDepth > 0) {
  46. context.report({
  47. messageId: 'conditionalExpect',
  48. node
  49. });
  50. }
  51. if (inPromiseCatch && (0, _utils.isExpectCall)(node)) {
  52. context.report({
  53. messageId: 'conditionalExpect',
  54. node
  55. });
  56. }
  57. },
  58. 'CallExpression:exit'(node) {
  59. if ((0, _utils.isTestCaseCall)(node)) {
  60. inTestCase = false;
  61. }
  62. if (isCatchCall(node)) {
  63. inPromiseCatch = false;
  64. }
  65. },
  66. CatchClause: increaseConditionalDepth,
  67. 'CatchClause:exit': decreaseConditionalDepth,
  68. IfStatement: increaseConditionalDepth,
  69. 'IfStatement:exit': decreaseConditionalDepth,
  70. SwitchStatement: increaseConditionalDepth,
  71. 'SwitchStatement:exit': decreaseConditionalDepth,
  72. ConditionalExpression: increaseConditionalDepth,
  73. 'ConditionalExpression:exit': decreaseConditionalDepth,
  74. LogicalExpression: increaseConditionalDepth,
  75. 'LogicalExpression:exit': decreaseConditionalDepth
  76. };
  77. }
  78. });
  79. exports.default = _default;