-
Notifications
You must be signed in to change notification settings - Fork 227
/
no-try-expect.ts
61 lines (58 loc) · 1.45 KB
/
no-try-expect.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { TSESTree } from '@typescript-eslint/experimental-utils';
import { createRule, isTestCase } from './tsUtils';
export default createRule({
name: __filename,
meta: {
docs: {
description: 'Prefer using toThrow for exception tests',
category: 'Best Practices',
recommended: false,
},
messages: {
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(' '),
},
type: 'problem',
schema: [],
},
defaultOptions: [],
create(context) {
let isTest = false;
let catchDepth = 0;
function isThrowExpectCall(node: TSESTree.CallExpression) {
return (
catchDepth > 0 && 'name' in node.callee && node.callee.name === 'expect'
);
}
return {
CallExpression(node) {
if (isTestCase(node)) {
isTest = true;
} else if (isTest && isThrowExpectCall(node)) {
context.report({
messageId: 'noTryExpect',
node,
});
}
},
CatchClause() {
if (isTest) {
++catchDepth;
}
},
'CatchClause:exit'() {
if (isTest) {
--catchDepth;
}
},
'CallExpression:exit'(node) {
if (isTestCase(node)) {
isTest = false;
}
},
};
},
});