forked from jest-community/eslint-plugin-jest
/
no-try-expect.js
53 lines (50 loc) · 1.2 KB
/
no-try-expect.js
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
import { getDocsUrl, isTestCase } from './util';
export default {
meta: {
docs: {
description: 'Prefer using toThrow for exception tests',
uri: getDocsUrl(__filename),
},
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(' '),
},
},
create(context) {
let isTest = false;
let catchDepth = 0;
function isThrowExpectCall(node) {
return catchDepth > 0 && 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;
}
},
};
},
};