Why is this an issue?

Assertions are meant to verify that the actual behavior of the code under test matches the expected behavior. When an assertion compares values whose types cannot be equal, its result is predetermined. The assertion either always fails or always succeeds, and the test does not verify the intended behavior.

Strict equality comparisons, such as ===, !==, and identity-based assertion matchers, do not coerce values before comparison. For example, a string value is never strictly equal to a number value. Loose equality comparisons, such as == and !=, can coerce primitive values, but comparing unrelated object types still produces a predetermined result.

How to fix it in Vitest

Compare values that can actually be equal. If the test intentionally compares different representations of the same concept, convert one value before the assertion or assert a property that has the expected type.

Code examples

Noncompliant code example

import { expect, test } from "vitest";

test("assertions on dissimilar types", () => {
  const count: number = 1;
  const title: string = "1";
  const enabled: boolean = true;

  expect(title).toBe(count); // Noncompliant: "string" and "number" cannot be strictly equal
  expect(enabled).not.toEqual("true"); // Noncompliant: this assertion always succeeds
});

Compliant solution

import { expect, test } from "vitest";

test("assertions on matching types", () => {
  const count: number = 1;
  const title: string = "1";
  const enabled: boolean = true;

  expect(title).toBe(String(count));
  expect(enabled).toEqual(true);
});

How to fix it in Node.js

Compare values that have compatible types when using strict equality assertions. If the expected and actual values use different representations, convert one side before making the assertion.

Code examples

Noncompliant code example

import assert from "node:assert/strict";
import test from "node:test";

test("assertions on dissimilar types", () => {
  const count: number = 1;
  const title: string = "1";
  const enabled: boolean = true;
  const startedAt: Date = new Date();

  assert.strictEqual(count, title); // Noncompliant: this assertion always fails
  assert.notStrictEqual(enabled, 1); // Noncompliant: this assertion always succeeds
  assert.strictEqual(startedAt, 1); // Noncompliant: this assertion always fails
});

Compliant solution

import assert from "node:assert/strict";
import test from "node:test";

test("assertions on matching types", () => {
  const count: number = 1;
  const title: string = "1";
  const enabled: boolean = true;
  const startedAt: Date = new Date("2024-01-01T00:00:00.000Z");

  assert.strictEqual(count, Number(title));
  assert.strictEqual(enabled, true);
  assert.strictEqual(startedAt.getTime(), Date.parse("2024-01-01T00:00:00.000Z"));
});

Resources

Documentation

Related rules