Jest: hasBeenCalledWith passes if object was modified after initial mock function call

Created on 2 Aug 2019  路  3Comments  路  Source: facebook/jest

馃悰 Bug Report

When creating an object and passing it to a jest.fn mock function, and after the function invocation the object is modified, the object the function was called with also gets modified.

To Reproduce

Sample code:

const fn = jest.fn();

const testObj = { one: 'two'};

const expectedObj = { one: 'two', three: 'four'};

fn(testObj);

testObj.three = 'four';

expect(fn).toHaveBeenCalledWith(expectedObj);

Expected behavior

I expect this test case to fail, however it will pass.

Run npx envinfo --preset jest

Paste the results here:

  System:
    OS: macOS Sierra 10.12.6
    CPU: (8) x64 Intel(R) Core(TM) i7-4980HQ CPU @ 2.80GHz
  Binaries:
    Node: 10.13.0 - /usr/local/bin/node
    Yarn: 1.17.3 - /usr/local/bin/yarn
    npm: 6.9.0 - /usr/local/bin/npm
  npmPackages:
    jest: 24.8.0 => 24.8.0 
Bug Report Needs Repro Needs Triage

Most helpful comment

Mocks can't just always make copies of their arguments, because object identity might matter when comparing calls. So we have to store the original argument, and when the assertion happens, it is equal to the expected.

The reference in testObj and expectedObj is NOT the same one.
If object identity matters why is it doing a deep comparison?

All 3 comments

Mocks can't just always make copies of their arguments, because object identity might matter when comparing calls. So we have to store the original argument, and when the assertion happens, it is equal to the expected.

Mocks can't just always make copies of their arguments, because object identity might matter when comparing calls. So we have to store the original argument, and when the assertion happens, it is equal to the expected.

The reference in testObj and expectedObj is NOT the same one.
If object identity matters why is it doing a deep comparison?

Was this page helpful?
0 / 5 - 0 ratings