| 1 | # Suggest using `toBe()` for primitive literals (`prefer-to-be`)
|
|---|
| 2 |
|
|---|
| 3 | When asserting against primitive literals such as numbers and strings, the
|
|---|
| 4 | equality matchers all operate the same, but read slightly differently in code.
|
|---|
| 5 |
|
|---|
| 6 | This rule recommends using the `toBe` matcher in these situations, as it forms
|
|---|
| 7 | the most grammatically natural sentence. For `null`, `undefined`, and `NaN` this
|
|---|
| 8 | rule recommends using their specific `toBe` matchers, as they give better error
|
|---|
| 9 | messages as well.
|
|---|
| 10 |
|
|---|
| 11 | ## Rule details
|
|---|
| 12 |
|
|---|
| 13 | This rule triggers a warning if `toEqual()` or `toStrictEqual()` are used to
|
|---|
| 14 | assert a primitive literal value such as numbers, strings, and booleans.
|
|---|
| 15 |
|
|---|
| 16 | The following patterns are considered warnings:
|
|---|
| 17 |
|
|---|
| 18 | ```js
|
|---|
| 19 | expect(value).not.toEqual(5);
|
|---|
| 20 | expect(getMessage()).toStrictEqual('hello world');
|
|---|
| 21 | expect(loadMessage()).resolves.toEqual('hello world');
|
|---|
| 22 | ```
|
|---|
| 23 |
|
|---|
| 24 | The following pattern is not warning:
|
|---|
| 25 |
|
|---|
| 26 | ```js
|
|---|
| 27 | expect(value).not.toBe(5);
|
|---|
| 28 | expect(getMessage()).toBe('hello world');
|
|---|
| 29 | expect(loadMessage()).resolves.toBe('hello world');
|
|---|
| 30 | expect(didError).not.toBe(true);
|
|---|
| 31 |
|
|---|
| 32 | expect(catchError()).toStrictEqual({ message: 'oh noes!' });
|
|---|
| 33 | ```
|
|---|
| 34 |
|
|---|
| 35 | For `null`, `undefined`, and `NaN`, this rule triggers a warning if `toBe` is
|
|---|
| 36 | used to assert against those literal values instead of their more specific
|
|---|
| 37 | `toBe` counterparts:
|
|---|
| 38 |
|
|---|
| 39 | ```js
|
|---|
| 40 | expect(value).not.toBe(undefined);
|
|---|
| 41 | expect(getMessage()).toBe(null);
|
|---|
| 42 | expect(countMessages()).resolves.not.toBe(NaN);
|
|---|
| 43 | ```
|
|---|
| 44 |
|
|---|
| 45 | The following pattern is not warning:
|
|---|
| 46 |
|
|---|
| 47 | ```js
|
|---|
| 48 | expect(value).toBeDefined();
|
|---|
| 49 | expect(getMessage()).toBeNull();
|
|---|
| 50 | expect(countMessages()).resolves.not.toBeNaN();
|
|---|
| 51 |
|
|---|
| 52 | expect(catchError()).toStrictEqual({ message: undefined });
|
|---|
| 53 | ```
|
|---|