| 1 | # Suggest using the built-in comparison matchers (`prefer-comparison-matcher`)
|
|---|
| 2 |
|
|---|
| 3 | Jest has a number of built-in matchers for comparing numbers which allow for
|
|---|
| 4 | more readable tests and error messages if an expectation fails.
|
|---|
| 5 |
|
|---|
| 6 | ## Rule details
|
|---|
| 7 |
|
|---|
| 8 | This rule checks for comparisons in tests that could be replaced with one of the
|
|---|
| 9 | following built-in comparison matchers:
|
|---|
| 10 |
|
|---|
| 11 | - `toBeGreaterThan`
|
|---|
| 12 | - `toBeGreaterThanOrEqual`
|
|---|
| 13 | - `toBeLessThan`
|
|---|
| 14 | - `toBeLessThanOrEqual`
|
|---|
| 15 |
|
|---|
| 16 | Examples of **incorrect** code for this rule:
|
|---|
| 17 |
|
|---|
| 18 | ```js
|
|---|
| 19 | expect(x > 5).toBe(true);
|
|---|
| 20 | expect(x < 7).not.toEqual(true);
|
|---|
| 21 | expect(x <= y).toStrictEqual(true);
|
|---|
| 22 | ```
|
|---|
| 23 |
|
|---|
| 24 | Examples of **correct** code for this rule:
|
|---|
| 25 |
|
|---|
| 26 | ```js
|
|---|
| 27 | expect(x).toBeGreaterThan(5);
|
|---|
| 28 | expect(x).not.toBeLessThanOrEqual(7);
|
|---|
| 29 | expect(x).toBeLessThanOrEqual(y);
|
|---|
| 30 |
|
|---|
| 31 | // special case - see below
|
|---|
| 32 | expect(x < 'Carl').toBe(true);
|
|---|
| 33 | ```
|
|---|
| 34 |
|
|---|
| 35 | Note that these matchers only work with numbers and bigints, and that the rule
|
|---|
| 36 | assumes that any variables on either side of the comparison operator are of one
|
|---|
| 37 | of those types - this means if you're using the comparison operator with
|
|---|
| 38 | strings, the fix applied by this rule will result in an error.
|
|---|
| 39 |
|
|---|
| 40 | ```js
|
|---|
| 41 | expect(myName).toBeGreaterThanOrEqual(theirName); // Matcher error: received value must be a number or bigint
|
|---|
| 42 | ```
|
|---|
| 43 |
|
|---|
| 44 | The reason for this is that comparing strings with these operators is expected
|
|---|
| 45 | to be very rare and would mean not being able to have an automatic fixer for
|
|---|
| 46 | this rule.
|
|---|
| 47 |
|
|---|
| 48 | If for some reason you are using these operators to compare strings, you can
|
|---|
| 49 | disable this rule using an inline
|
|---|
| 50 | [configuration comment](https://eslint.org/docs/user-guide/configuring/rules#disabling-rules):
|
|---|
| 51 |
|
|---|
| 52 | ```js
|
|---|
| 53 | // eslint-disable-next-line jest/prefer-comparison-matcher
|
|---|
| 54 | expect(myName > theirName).toBe(true);
|
|---|
| 55 | ```
|
|---|