-
Notifications
You must be signed in to change notification settings - Fork 227
/
prefer-expect-assertions.ts
89 lines (77 loc) · 2.57 KB
/
prefer-expect-assertions.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import {
AST_NODE_TYPES,
TSESTree,
} from '@typescript-eslint/experimental-utils';
import { createRule, getAccessorValue, isSupportedAccessor } from './utils';
const isExpectAssertionsOrHasAssertionsCall = (expression: TSESTree.Node) => {
if (
expression.type !== AST_NODE_TYPES.CallExpression ||
expression.callee.type !== AST_NODE_TYPES.MemberExpression ||
!isSupportedAccessor(expression.callee.object, 'expect') ||
!isSupportedAccessor(expression.callee.property)
) {
return false;
}
const expectAssertionName = getAccessorValue(expression.callee.property);
if (expectAssertionName !== 'assertions') {
return expectAssertionName === 'hasAssertions';
}
const [arg] = expression.arguments;
return (
expression.arguments &&
expression.arguments.length === 1 &&
arg.type === AST_NODE_TYPES.Literal &&
typeof arg.value === 'number' &&
Number.isInteger(arg.value)
);
};
const getFunctionFirstLine = (functionBody: [TSESTree.ExpressionStatement]) =>
functionBody[0] && functionBody[0].expression;
const isFirstLineExprStmt = (
functionBody: TSESTree.Statement[],
): functionBody is [TSESTree.ExpressionStatement] =>
functionBody[0] &&
functionBody[0].type === AST_NODE_TYPES.ExpressionStatement;
interface PreferExpectAssertionsCallExpression extends TSESTree.CallExpression {
// prettier-ignore
// WEB-40105
arguments: [
TSESTree.Expression,
TSESTree.ArrowFunctionExpression & { body: TSESTree.BlockStatement }
];
}
export default createRule({
name: __filename,
meta: {
docs: {
category: 'Best Practices',
description:
'Suggest using `expect.assertions()` OR `expect.hasAssertions()`',
recommended: false,
},
messages: {
haveExpectAssertions:
'Every test should have either `expect.assertions(<number of assertions>)` or `expect.hasAssertions()` as its first expression',
},
type: 'suggestion',
schema: [],
},
defaultOptions: [],
create(context) {
return {
'CallExpression[callee.name=/^(it|test)$/][arguments.1.body.body]'(
node: PreferExpectAssertionsCallExpression,
) {
const testFuncBody = node.arguments[1].body.body;
if (!isFirstLineExprStmt(testFuncBody)) {
context.report({ messageId: 'haveExpectAssertions', node });
return;
}
const testFuncFirstLine = getFunctionFirstLine(testFuncBody);
if (!isExpectAssertionsOrHasAssertionsCall(testFuncFirstLine)) {
context.report({ messageId: 'haveExpectAssertions', node });
}
},
};
},
});