marchaos / jest-mock-extended

Type safe mocking extensions for Jest https://www.npmjs.com/package/jest-mock-extended
MIT License
810 stars 56 forks source link

How to deep-compare objects with `calledWith`? #118

Open smaspe opened 1 year ago

smaspe commented 1 year ago

Many functions expect an object as input parameter. calledWith relies on strict equality. expect.objectContaining is a partial match.

Is there a way to perform a deep object comparison? Am I missing a built-in matcher, or should I create on myself?

Example:

describe("foo", () => {
  it("bar", () => {
    const sud = mockDeep<{
      test: (input: { a: number; b: string }) => number;
    }>();

    sud.test.calledWith({ a: 2, b: "42" }).mockReturnValue(42);

    // This fails because the objects are not strictly equal
    expect(sud.test({ a: 2, b: "42" })).toBe(42);
  });
});
maxy9 commented 9 months ago

Hey @smaspe, as you can see I have put in a PR for this issue, but I was just wondering if you used a workaround in the meantime?

This is the workaround I am currently using to match my object parameter:

const buildObjectMatcher = (expectedInput) => new Matcher((actual) => JSON.stringify(actual) === JSON.stringify(expectedInput), 'object-matcher')

const myObj = {
  myFn: (p1: Object, p2: Primitive) => {} //pseudo-types
};

const expectedInput1 = { an: 'object' };
const expectedInput2 = 'primitive';
myObj.myFn.calledWith(buildObjectMatcher(expectedInput1), expectedInput2).mockResolvedValue(response);