jestjs/jest

[Bug]: toHaveBeenCalledWith matcher matches with any URL object

yatki opened this issue · 7 comments

Version

29.7.0

Steps to reproduce

Please run the test below

it('toHaveBeenCalledWith not working with URL object', () => {
    const spy = jest.fn()

    spy(new URL('http://demo'))

    expect(spy).toHaveBeenCalledWith(new URL('http://demo'))
    expect(spy).toHaveBeenCalledWith(new URL('http://demo2'))
    expect(spy).toHaveBeenCalledWith(new URL('http://demo3'))
  })

Expected behavior

I either expect the last 2 assertions to fail or since the object references are different, I expect all assertions to fail.

Actual behavior

But all assertions pass.

Additional context

No response

Environment

MacOS 14.4.1

We can see the same behavior when trying to compare URL objects, with toEqual (which is used by toHaveBeenCalledWith)

it("toEqual not working with URL object", () => {
    expect(new URL("http://demo")).toEqual(new URL("http://demo2"));
});

according to the documentation .toEqual should use Object.is, which can differentiate between two URLs though

Object.is(new URL("http://demo"), new URL("http://demo2"));
> false

Also based on this line, URL object would be compared based on href attribute but seems like it's not working like that neither.