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.
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);
I expect this test case to fail, however it will pass.
npx envinfo --preset jestPaste 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
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?
Most helpful comment
The reference in testObj and expectedObj is NOT the same one.
If object identity matters why is it doing a deep comparison?