Skip to content

[new-rule] recommend toBe over toEqual when expecting primitive literals #801

@G-Rath

Description

@G-Rath

As far as I know, there's nearly no difference in using toBe over toEqual when the expected value is a primitive literal, i.e

expect(response.statusCode).toBe(200);
// vs
expect(response.statusCode).toEqual(200);
expect(response.statusCode).toStrictEqual(200);

expect(isValid(obj)).toBe(true);
// vs
expect(isValid(obj)).toEqual(true);
expect(isValid(obj)).toStrictEqual(true);

expect(join(['hello', 'world')).toBe('hello world');
// vs
expect(join(['hello', 'world')).toEqual('hello world');
expect(join(['hello', 'world')).toStrictEqual('hello world');

IMO toBe(200) reads better than toEqual(200) (or toStrictEqual(200)).

It would be nice to have a rule that checked for toEqual matchers that were being passed primitive literal values, and recommended replacing them with toBe.

This would not apply if you're expecting an object or array literal, nor the value of a variable (even if we could resolve that variable back to a literal, i.e if its const status = 200;).

We also probably shouldn't be reporting on floats? (which we could create prefer-to-be-close-to) - alternatively I don't think it'd be much of a stretch if prefer-to-be supported floats.

my quick test setup to compare the three matchers
describe.each<[a: unknown, b: unknown]>([
  [1, 2],
  [1, 1],
  ['', ''],
  ['a', 'b'],
  ['a', 'a'],
  [{ x: 1 }, { x: 2 }],
  [{ x: 1 }, { x: 1 }],
  [{ x: { y: 1 } }, { x: { y: 2 } }],
  [{ x: { y: 1 } }, { x: { y: 1 } }],
  [[1], [2]],
  [[1], [1]],
  [[{ x: { y: 1 } }], [{ x: { y: 2 } }]]
])('%# %s vs %s', (a, b) => {
  test('toBe', () => {
    expect(a).toBe(b);
  });

  test('toEqual', () => {
    expect(a).toEqual(b);
  });

  test('toStrictEqual', () => {
    expect(a).toStrictEqual(b);
  });
});

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions