| 1 | # Prefer `await expect(...).resolves` over `expect(await ...)` syntax (`prefer-expect-resolves`)
|
|---|
| 2 |
|
|---|
| 3 | When working with promises, there are two primary ways you can test the resolved
|
|---|
| 4 | value:
|
|---|
| 5 |
|
|---|
| 6 | 1. use the `resolve` modifier on `expect`
|
|---|
| 7 | (`await expect(...).resolves.<matcher>` style)
|
|---|
| 8 | 2. `await` the promise and assert against its result
|
|---|
| 9 | (`expect(await ...).<matcher>` style)
|
|---|
| 10 |
|
|---|
| 11 | While the second style is arguably less dependent on `jest`, if the promise
|
|---|
| 12 | rejects it will be treated as a general error, resulting in less predictable
|
|---|
| 13 | behaviour and output from `jest`.
|
|---|
| 14 |
|
|---|
| 15 | Additionally, favoring the first style ensures consistency with its `rejects`
|
|---|
| 16 | counterpart, as there is no way of "awaiting" a rejection.
|
|---|
| 17 |
|
|---|
| 18 | ## Rule details
|
|---|
| 19 |
|
|---|
| 20 | This rule triggers a warning if an `await` is done within an `expect`, and
|
|---|
| 21 | recommends using `resolves` instead.
|
|---|
| 22 |
|
|---|
| 23 | Examples of **incorrect** code for this rule
|
|---|
| 24 |
|
|---|
| 25 | ```js
|
|---|
| 26 | it('passes', async () => {
|
|---|
| 27 | expect(await someValue()).toBe(true);
|
|---|
| 28 | });
|
|---|
| 29 |
|
|---|
| 30 | it('is true', async () => {
|
|---|
| 31 | const myPromise = Promise.resolve(true);
|
|---|
| 32 |
|
|---|
| 33 | expect(await myPromise).toBe(true);
|
|---|
| 34 | });
|
|---|
| 35 | ```
|
|---|
| 36 |
|
|---|
| 37 | Examples of **correct** code for this rule
|
|---|
| 38 |
|
|---|
| 39 | ```js
|
|---|
| 40 | it('passes', async () => {
|
|---|
| 41 | await expect(someValue()).resolves.toBe(true);
|
|---|
| 42 | });
|
|---|
| 43 |
|
|---|
| 44 | it('is true', async () => {
|
|---|
| 45 | const myPromise = Promise.resolve(true);
|
|---|
| 46 |
|
|---|
| 47 | await expect(myPromise).resolves.toBe(true);
|
|---|
| 48 | });
|
|---|
| 49 |
|
|---|
| 50 | it('errors', async () => {
|
|---|
| 51 | await expect(Promise.rejects('oh noes!')).rejects.toThrow('oh noes!');
|
|---|
| 52 | });
|
|---|
| 53 | ```
|
|---|