no-try-expect.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _utils = require("./utils");
  7. var _default = (0, _utils.createRule)({
  8. name: __filename,
  9. meta: {
  10. docs: {
  11. description: 'Prefer using toThrow for exception tests',
  12. category: 'Best Practices',
  13. recommended: 'error'
  14. },
  15. deprecated: true,
  16. replacedBy: ['no-conditional-expect'],
  17. messages: {
  18. noTryExpect: ['Tests should use Jest‘s exception helpers.', 'Use "expect(() => yourFunction()).toThrow()" for synchronous tests,', 'or "await expect(yourFunction()).rejects.toThrow()" for async tests'].join(' ')
  19. },
  20. type: 'problem',
  21. schema: []
  22. },
  23. defaultOptions: [],
  24. create(context) {
  25. let isTest = false;
  26. let catchDepth = 0;
  27. function isThrowExpectCall(node) {
  28. return catchDepth > 0 && (0, _utils.isExpectCall)(node);
  29. }
  30. return {
  31. CallExpression(node) {
  32. if ((0, _utils.isTestCaseCall)(node)) {
  33. isTest = true;
  34. } else if (isTest && isThrowExpectCall(node)) {
  35. context.report({
  36. messageId: 'noTryExpect',
  37. node
  38. });
  39. }
  40. },
  41. FunctionDeclaration(node) {
  42. const declaredVariables = context.getDeclaredVariables(node);
  43. const testCallExpressions = (0, _utils.getTestCallExpressionsFromDeclaredVariables)(declaredVariables);
  44. if (testCallExpressions.length > 0) {
  45. isTest = true;
  46. }
  47. },
  48. CatchClause() {
  49. if (isTest) {
  50. ++catchDepth;
  51. }
  52. },
  53. 'CatchClause:exit'() {
  54. if (isTest) {
  55. --catchDepth;
  56. }
  57. },
  58. 'CallExpression:exit'(node) {
  59. if ((0, _utils.isTestCaseCall)(node)) {
  60. isTest = false;
  61. }
  62. },
  63. 'FunctionDeclaration:exit'(node) {
  64. const declaredVariables = context.getDeclaredVariables(node);
  65. const testCallExpressions = (0, _utils.getTestCallExpressionsFromDeclaredVariables)(declaredVariables);
  66. if (testCallExpressions.length > 0) {
  67. isTest = false;
  68. }
  69. }
  70. };
  71. }
  72. });
  73. exports.default = _default;