Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(prefer-expect-assertions): support requiring only if expect is used in a loop #1013

Merged
merged 6 commits into from Jan 15, 2022
Merged
60 changes: 60 additions & 0 deletions docs/rules/prefer-expect-assertions.md
Expand Up @@ -58,6 +58,16 @@ test('my test', () => {

## Options

This rule can be configured to only check tests that match certain patterns that
typically look like `expect` calls might be missed, such as in promises or
loops.

By default, none of these options are enabled meaning the rule checks _every_
test for a call to either `expect.hasAssertions` or `expect.assertions`. If any
of the options are enabled the rule checks any test that matches _at least one_
of the patterns represented by the enabled options (think "OR" rather than
"AND").

#### `onlyFunctionsWithAsyncKeyword`

When `true`, this rule will only warn for tests that use the `async` keyword.
Expand Down Expand Up @@ -97,3 +107,53 @@ test('my test', async () => {
expect(result).toBe('foo');
});
```

#### `onlyFunctionsWithExpectInLoop`

When `true`, this rule will only warn for tests that have `expect` calls within
a native loop.

```json
{
"rules": {
"jest/prefer-expect-assertions": [
"warn",
{ "onlyFunctionsWithAsyncKeyword": true }
]
}
}
```

Examples of **incorrect** code when `'onlyFunctionsWithExpectInLoop'` is `true`:

```js
describe('getNumbers', () => {
it('only returns numbers that are greater than zero', () => {
const numbers = getNumbers();

for (const number in numbers) {
expect(number).toBeGreaterThan(0);
}
});
});
```

Examples of **correct** code when `'onlyFunctionsWithExpectInLoop'` is `true`:

```js
describe('getNumbers', () => {
it('only returns numbers that are greater than zero', () => {
expect.hasAssertions();

const numbers = getNumbers();

for (const number in numbers) {
expect(number).toBeGreaterThan(0);
}
});

it('returns more than one number', () => {
expect(getNumbers().length).toBeGreaterThan(1);
});
});
```