Skip to content

Commit

Permalink
feat(prefer-expect-assertions): support requiring only if expect is…
Browse files Browse the repository at this point in the history
… 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
  • Loading branch information
G-Rath committed Jan 15, 2022
1 parent 237b551 commit e6f4f8a
Show file tree
Hide file tree
Showing 3 changed files with 722 additions and 16 deletions.
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);
});
});
```

0 comments on commit e6f4f8a

Please sign in to comment.