Skip to content

Commit e6f4f8a

Browse files
authored
feat(prefer-expect-assertions): support requiring only if expect is used in a loop (#1013)
* feat(prefer-expect-assertions): support requiring only if `expect` is used in a loop * test(prefer-expect-assertions): add cases for each * chore(prefer-expect-assertions): add default value for `onlyFunctionsWithExpectInLoop` option * test(prefer-expect-assertions): adjust some cases * fix(prefer-expect-assertions): report expects in loops in functions in tests * test(prefer-expect-assertions): format cases a bit
1 parent 237b551 commit e6f4f8a

File tree

3 files changed

+722
-16
lines changed

3 files changed

+722
-16
lines changed

docs/rules/prefer-expect-assertions.md

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,16 @@ test('my test', () => {
5858

5959
## Options
6060

61+
This rule can be configured to only check tests that match certain patterns that
62+
typically look like `expect` calls might be missed, such as in promises or
63+
loops.
64+
65+
By default, none of these options are enabled meaning the rule checks _every_
66+
test for a call to either `expect.hasAssertions` or `expect.assertions`. If any
67+
of the options are enabled the rule checks any test that matches _at least one_
68+
of the patterns represented by the enabled options (think "OR" rather than
69+
"AND").
70+
6171
#### `onlyFunctionsWithAsyncKeyword`
6272

6373
When `true`, this rule will only warn for tests that use the `async` keyword.
@@ -97,3 +107,53 @@ test('my test', async () => {
97107
expect(result).toBe('foo');
98108
});
99109
```
110+
111+
#### `onlyFunctionsWithExpectInLoop`
112+
113+
When `true`, this rule will only warn for tests that have `expect` calls within
114+
a native loop.
115+
116+
```json
117+
{
118+
"rules": {
119+
"jest/prefer-expect-assertions": [
120+
"warn",
121+
{ "onlyFunctionsWithAsyncKeyword": true }
122+
]
123+
}
124+
}
125+
```
126+
127+
Examples of **incorrect** code when `'onlyFunctionsWithExpectInLoop'` is `true`:
128+
129+
```js
130+
describe('getNumbers', () => {
131+
it('only returns numbers that are greater than zero', () => {
132+
const numbers = getNumbers();
133+
134+
for (const number in numbers) {
135+
expect(number).toBeGreaterThan(0);
136+
}
137+
});
138+
});
139+
```
140+
141+
Examples of **correct** code when `'onlyFunctionsWithExpectInLoop'` is `true`:
142+
143+
```js
144+
describe('getNumbers', () => {
145+
it('only returns numbers that are greater than zero', () => {
146+
expect.hasAssertions();
147+
148+
const numbers = getNumbers();
149+
150+
for (const number in numbers) {
151+
expect(number).toBeGreaterThan(0);
152+
}
153+
});
154+
155+
it('returns more than one number', () => {
156+
expect(getNumbers().length).toBeGreaterThan(1);
157+
});
158+
});
159+
```

0 commit comments

Comments
 (0)