Skip to content

Show warning if toEqual compares the object which Object.keys returns empty array for #9542

@sevenc-nanashi

Description

@sevenc-nanashi

Clear and concise description of the problem

I was using vitest for test for React Router application.
I noticed that Object.keys(Response) returns [], thus it doesn't check anything but whether both objects are response.

This means, this test passes:

test("hoge", () => {
  const r1 = new Response("hoge", { status: 200 });
  const r2 = new Response(null, { status: 404 });
  expect(r1).toEqual(r2);
});

Which is clearly a false-negative.

Suggested solution

It would be difficult to prepare matchers for all objects, but it would be helpful if vitest shows warning if nothing is compared (except plain empty object: {}).

Simple PoC:

import { test, expect } from "vitest";

const isPlainObject = (obj: unknown) => {
  return obj.constructor === Object || Object.getPrototypeOf(obj) === null;
};
expect.addEqualityTesters([
  (a: unknown, b: unknown) => {
    if (
      Object.keys(a).length === 0 &&
      !isPlainObject(a) &&
      Object.keys(b).length === 0 &&
      !isPlainObject(b)
    ) {
      console.log("Warning: Comparing two empty non-plain objects, causing false-negative results.");
    }
    return undefined;
  },
]);

test("hoge", () => {
  const r1 = new Response("hoge", { status: 200 });
  const r2 = new Response(null, { status: 200 });
  expect(r1).toEqual(r2);
});

Alternative

No response

Additional context

related: #9522, #7991

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

    p2-nice-to-haveNot breaking anything but nice to have (priority)

    Projects

    Status

    Has plan

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions