jestjs / jest

Delightful JavaScript Testing.
https://jestjs.io
MIT License
44.29k stars 6.47k forks source link

[Bug]: Incorrect comparison with calledWith(objectContaining) and multiple calls #15342

Open glenjamin opened 1 month ago

glenjamin commented 1 month ago

Version

30.0.0-alpha6

Steps to reproduce

describe('something', () => {
  it('should work', () => {
    const f = jest.fn();
    f({ a: 1, b: 2 });
    f({ a: 3, b: 7 });

    expect(f).toHaveBeenCalledWith(expect.objectContaining({ b: 7 }));
  });
});

Expected behavior

Test passes

Actual behavior

 FAIL  ./demo.test.js
  something
    ✕ should work (38 ms)

  ● something › should work

    expect(jest.fn()).toHaveBeenCalledWith(...expected)

    Expected: ObjectContaining {"a": 1, "b": 7}
    Received
           1: {"a": 1, "b": 2}
           2: {"a": 3, "b": 7}

    Number of calls: 2

       5 |     f({ a: 3, b: 7 });
       6 |
    >  7 |     expect(f).toHaveBeenCalledWith(expect.objectContaining({ b: 7 }));
         |               ^
       8 |   });
       9 | });
      10 |

      at Object.toHaveBeenCalledWith (demo.test.js:7:15)

Additional context

I've traced this back to https://github.com/jestjs/jest/commit/169ba834126945aa252043008b9211229f9ba20b#diff-f8846ea7aae48b4baadb9c50ba129cdadc6783e6051e605b5e2827153fc04479R253

The assumption that this.sample is safe to modify is incorrect.

I expect that this will fail in any scenario where objectContaining is compared against multiple values

cc @colinacassidy who supplied the previous fix

Environment

System:
    OS: macOS 14.6.1
    CPU: (8) x64 Intel(R) Core(TM) i7-1068NG7 CPU @ 2.30GHz
  Binaries:
    Node: 20.11.1 - ~/.asdf/installs/nodejs/20.11.1/bin/node
    Yarn: 1.22.21 - ~/.asdf/installs/nodejs/20.11.1/bin/yarn
    npm: 10.2.4 - ~/.asdf/plugins/nodejs/shims/npm
    pnpm: 8.11.0 - ~/.asdf/installs/nodejs/20.11.1/bin/pnpm
  npmPackages:
    jest: ^30.0.0-alpha.6 => 30.0.0-alpha.6
github-actions[bot] commented 2 weeks ago

This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 30 days.

glenjamin commented 1 week ago

not stale

marcusds commented 1 week ago

Can confirm commenting out the lines changed in commit 169ba83 fixes this issue for me.