jest/prefer-to-be
Require toBe() for primitive literals, and toBeNull(), toBeUndefined(), toBeNaN()
fixable
toEqual() and toStrictEqual() compare objects property by property. For a string, a number or a boolean, they do the same check as toBe(), and toBe() tells the reader that you expect one plain value. null, undefined and NaN have matchers that name the value.
| Written | Use instead |
|---|---|
toEqual(2), toStrictEqual("config") | toBe(2), toBe("config") |
toBe(null), toEqual(null) | toBeNull() |
toBe(undefined), not.toBeDefined() | toBeUndefined() |
not.toBe(undefined), not.toBeUndefined() | toBeDefined() |
toBe(NaN), toEqual(NaN) | toBeNaN() |
--fix rewrites the matcher.
Configure#
Off by default. To turn it on:
bunfig.toml
[lint.rules]
"jest/prefer-to-be" = "error" # or "warn"Examples#
example.ts7 problems
import { expect, test } from "@jest/globals";
test("parses the header", () => {
expect(header.version).toEqualUse toBe when expecting primitive literals.(2);
expect(header.name).toStrictEqualUse toBe when expecting primitive literals.("config");
expect(header.parent).toBe(null)Use toBeNull instead.;
expect(header.comment).not.toBeDefined()Use toBeUndefined instead.;
expect(header.size).not.toBe(undefined)Use toBeDefined instead.;
expect(header.date).not.toBeUndefined()Use toBeDefined instead.;
expect(header.ratio).toEqual(NaN)Use toBeNaN instead.;
});example.tsNo problems
import { expect, test } from "@jest/globals";
test("parses the header", () => {
expect(header.version).toBe(2);
expect(header.name).toBe("config");
expect(header.parent).toBeNull();
expect(header.comment).toBeUndefined();
expect(header.size).toBeDefined();
expect(header.date).toBeDefined();
expect(header.ratio).toBeNaN();
});Only literals count. Objects, arrays and variables are left alone:
example.tsNo problems
import { expect, test } from "@jest/globals";
test("parses the body", () => {
expect(body.tags).toEqual(["a", "b"]);
expect(body.length).toEqual(expectedLength);
});