valid-expect.js
9.02 KB
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _experimentalUtils = require("@typescript-eslint/experimental-utils");
var _utils = require("./utils");
/*
* This implementation is ported from from eslint-plugin-jasmine.
* MIT license, Tom Vincent.
*/
/**
* Async assertions might be called in Promise
* methods like `Promise.x(expect1)` or `Promise.x([expect1, expect2])`.
* If that's the case, Promise node have to be awaited or returned.
*
* @Returns CallExpressionNode
*/
const getPromiseCallExpressionNode = node => {
if (node.type === _experimentalUtils.AST_NODE_TYPES.ArrayExpression && node.parent && node.parent.type === _experimentalUtils.AST_NODE_TYPES.CallExpression) {
node = node.parent;
}
if (node.type === _experimentalUtils.AST_NODE_TYPES.CallExpression && node.callee.type === _experimentalUtils.AST_NODE_TYPES.MemberExpression && (0, _utils.isSupportedAccessor)(node.callee.object) && (0, _utils.getAccessorValue)(node.callee.object) === 'Promise' && node.parent) {
return node;
}
return null;
};
const findPromiseCallExpressionNode = node => {
var _node$parent;
return (_node$parent = node.parent) !== null && _node$parent !== void 0 && _node$parent.parent && [_experimentalUtils.AST_NODE_TYPES.CallExpression, _experimentalUtils.AST_NODE_TYPES.ArrayExpression].includes(node.parent.type) ? getPromiseCallExpressionNode(node.parent) : null;
};
const getParentIfThenified = node => {
var _node$parent2;
const grandParentNode = (_node$parent2 = node.parent) === null || _node$parent2 === void 0 ? void 0 : _node$parent2.parent;
if (grandParentNode && grandParentNode.type === _experimentalUtils.AST_NODE_TYPES.CallExpression && (0, _utils.isExpectMember)(grandParentNode.callee) && ['then', 'catch'].includes((0, _utils.getAccessorValue)(grandParentNode.callee.property)) && grandParentNode.parent) {
// Just in case `then`s are chained look one above.
return getParentIfThenified(grandParentNode);
}
return node;
};
const isAcceptableReturnNode = (node, allowReturn) => {
if (allowReturn && node.type === _experimentalUtils.AST_NODE_TYPES.ReturnStatement) {
return true;
}
if (node.type === _experimentalUtils.AST_NODE_TYPES.ConditionalExpression && node.parent) {
return isAcceptableReturnNode(node.parent, allowReturn);
}
return [_experimentalUtils.AST_NODE_TYPES.ArrowFunctionExpression, _experimentalUtils.AST_NODE_TYPES.AwaitExpression].includes(node.type);
};
const isNoAssertionsParentNode = node => node.type === _experimentalUtils.AST_NODE_TYPES.ExpressionStatement || node.type === _experimentalUtils.AST_NODE_TYPES.AwaitExpression && node.parent !== undefined && node.parent.type === _experimentalUtils.AST_NODE_TYPES.ExpressionStatement;
const promiseArrayExceptionKey = ({
start,
end
}) => `${start.line}:${start.column}-${end.line}:${end.column}`;
const defaultAsyncMatchers = ['toReject', 'toResolve'];
var _default = (0, _utils.createRule)({
name: __filename,
meta: {
docs: {
category: 'Best Practices',
description: 'Enforce valid `expect()` usage',
recommended: 'error'
},
messages: {
tooManyArgs: 'Expect takes at most {{ amount }} argument{{ s }}.',
notEnoughArgs: 'Expect requires at least {{ amount }} argument{{ s }}.',
modifierUnknown: 'Expect has no modifier named "{{ modifierName }}".',
matcherNotFound: 'Expect must have a corresponding matcher call.',
matcherNotCalled: 'Matchers must be called to assert.',
asyncMustBeAwaited: 'Async assertions must be awaited{{ orReturned }}.',
promisesWithAsyncAssertionsMustBeAwaited: 'Promises which return async assertions must be awaited{{ orReturned }}.'
},
type: 'suggestion',
schema: [{
type: 'object',
properties: {
alwaysAwait: {
type: 'boolean',
default: false
},
asyncMatchers: {
type: 'array',
items: {
type: 'string'
}
},
minArgs: {
type: 'number',
minimum: 1
},
maxArgs: {
type: 'number',
minimum: 1
}
},
additionalProperties: false
}]
},
defaultOptions: [{
alwaysAwait: false,
asyncMatchers: defaultAsyncMatchers,
minArgs: 1,
maxArgs: 1
}],
create(context, [{
alwaysAwait,
asyncMatchers = defaultAsyncMatchers,
minArgs = 1,
maxArgs = 1
}]) {
// Context state
const arrayExceptions = new Set();
const pushPromiseArrayException = loc => arrayExceptions.add(promiseArrayExceptionKey(loc));
/**
* Promise method that accepts an array of promises,
* (eg. Promise.all), will throw warnings for the each
* unawaited or non-returned promise. To avoid throwing
* multiple warnings, we check if there is a warning in
* the given location.
*/
const promiseArrayExceptionExists = loc => arrayExceptions.has(promiseArrayExceptionKey(loc));
return {
CallExpression(node) {
if (!(0, _utils.isExpectCall)(node)) {
return;
}
const {
expect,
modifier,
matcher
} = (0, _utils.parseExpectCall)(node);
if (expect.arguments.length < minArgs) {
const expectLength = (0, _utils.getAccessorValue)(expect.callee).length;
const loc = {
start: {
column: node.loc.start.column + expectLength,
line: node.loc.start.line
},
end: {
column: node.loc.start.column + expectLength + 1,
line: node.loc.start.line
}
};
context.report({
messageId: 'notEnoughArgs',
data: {
amount: minArgs,
s: minArgs === 1 ? '' : 's'
},
node,
loc
});
}
if (expect.arguments.length > maxArgs) {
const {
start
} = expect.arguments[maxArgs].loc;
const {
end
} = expect.arguments[node.arguments.length - 1].loc;
const loc = {
start,
end: {
column: end.column - 1,
line: end.line
}
};
context.report({
messageId: 'tooManyArgs',
data: {
amount: maxArgs,
s: maxArgs === 1 ? '' : 's'
},
node,
loc
});
} // something was called on `expect()`
if (!matcher) {
if (modifier) {
context.report({
messageId: 'matcherNotFound',
node: modifier.node.property
});
}
return;
}
if ((0, _utils.isExpectMember)(matcher.node.parent)) {
context.report({
messageId: 'modifierUnknown',
data: {
modifierName: matcher.name
},
node: matcher.node.property
});
return;
}
if (!matcher.arguments) {
context.report({
messageId: 'matcherNotCalled',
node: matcher.node.property
});
}
const parentNode = matcher.node.parent;
const shouldBeAwaited = modifier && modifier.name !== _utils.ModifierName.not || asyncMatchers.includes(matcher.name);
if (!parentNode.parent || !shouldBeAwaited) {
return;
}
/**
* If parent node is an array expression, we'll report the warning,
* for the array object, not for each individual assertion.
*/
const isParentArrayExpression = parentNode.parent.type === _experimentalUtils.AST_NODE_TYPES.ArrayExpression;
const orReturned = alwaysAwait ? '' : ' or returned';
/**
* An async assertion can be chained with `then` or `catch` statements.
* In that case our target CallExpression node is the one with
* the last `then` or `catch` statement.
*/
const targetNode = getParentIfThenified(parentNode);
const finalNode = findPromiseCallExpressionNode(targetNode) || targetNode;
if (finalNode.parent && // If node is not awaited or returned
!isAcceptableReturnNode(finalNode.parent, !alwaysAwait) && // if we didn't warn user already
!promiseArrayExceptionExists(finalNode.loc)) {
context.report({
loc: finalNode.loc,
data: {
orReturned
},
messageId: finalNode === targetNode ? 'asyncMustBeAwaited' : 'promisesWithAsyncAssertionsMustBeAwaited',
node
});
if (isParentArrayExpression) {
pushPromiseArrayException(finalNode.loc);
}
}
},
// nothing called on "expect()"
'CallExpression:exit'(node) {
if ((0, _utils.isExpectCall)(node) && isNoAssertionsParentNode(node.parent)) {
context.report({
messageId: 'matcherNotFound',
node
});
}
}
};
}
});
exports.default = _default;