-
Notifications
You must be signed in to change notification settings - Fork 236
/
prefer-expect-resolves.md
63 lines (45 loc) · 1.74 KB
/
prefer-expect-resolves.md
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
# Prefer `await expect(...).resolves` over `expect(await ...)` syntax (`prefer-expect-resolves`)
💼 This rule is enabled in the following
[configs](https://github.com/jest-community/eslint-plugin-jest/blob/main/README.md#shareable-configurations):
`all`.
🔧 This rule is automatically fixable using the `--fix`
[option](https://eslint.org/docs/latest/user-guide/command-line-interface#--fix)
on the command line.
<!-- end rule header -->
When working with promises, there are two primary ways you can test the resolved
value:
1. use the `resolve` modifier on `expect`
(`await expect(...).resolves.<matcher>` style)
2. `await` the promise and assert against its result
(`expect(await ...).<matcher>` style)
While the second style is arguably less dependent on `jest`, if the promise
rejects it will be treated as a general error, resulting in less predictable
behaviour and output from `jest`.
Additionally, favoring the first style ensures consistency with its `rejects`
counterpart, as there is no way of "awaiting" a rejection.
## Rule details
This rule triggers a warning if an `await` is done within an `expect`, and
recommends using `resolves` instead.
Examples of **incorrect** code for this rule
```js
it('passes', async () => {
expect(await someValue()).toBe(true);
});
it('is true', async () => {
const myPromise = Promise.resolve(true);
expect(await myPromise).toBe(true);
});
```
Examples of **correct** code for this rule
```js
it('passes', async () => {
await expect(someValue()).resolves.toBe(true);
});
it('is true', async () => {
const myPromise = Promise.resolve(true);
await expect(myPromise).resolves.toBe(true);
});
it('errors', async () => {
await expect(Promise.rejects('oh noes!')).rejects.toThrow('oh noes!');
});
```