Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

mock + toBeCalledWith function and modified objects #11219

Closed
mikamikuh opened this issue Mar 20, 2021 · 2 comments
Closed

mock + toBeCalledWith function and modified objects #11219

mikamikuh opened this issue Mar 20, 2021 · 2 comments

Comments

@mikamikuh
Copy link

馃悰 Bug Report

expect(mock).toBeCalledWith(...) function doesn't compare objects with the state when it was called. It seems to be holding the reference to the object, so when the mock function was called with an object reference to { a: 'foo' } and the object was updated afterwards, expect(mock).toBeCalledWith(...) compares with the latest state of the object, not { a: 'foo' }.

To Reproduce

Steps to reproduce the behavior:

Implementation with update obj after the fn function was called, so it should be called with { a: 'foo' }

const objectUpdate = (fn) => {
  const obj = {
    a: 'foo'
  }
  fn(obj)
  obj.b = 'bar'
}

and, in the test, pass jest.fn() to the fucntion (objectUpdate)

test ('Test with object update', () => {
  const mock = jest.fn()
  objectUpdate(mock)
  expect(mock).toBeCalledWith({
    a: 'foo'
  })
})

which fails with:

    - Expected
    + Received

      Object {
        "a": "foo",
    +   "b": "bar",
      },

Expected behavior

The test above should pass because when the fn function is called, the obj is just { a: 'foo' }.

Link to repl or repo (highly encouraged)

https://replit.com/@mikamikuh/jest-playground#object-update.js

envinfo

  System:
    OS: Linux 5.8 Ubuntu 20.04.2 LTS (Focal Fossa)
    CPU: (12) x64 AMD Ryzen 5 3600 6-Core Processor
  Binaries:
    Node: 12.13.0 - ~/.nvm/versions/node/v12.13.0/bin/node
    npm: 6.12.0 - ~/.nvm/versions/node/v12.13.0/bin/npm
@SimenB
Copy link
Member

SimenB commented Mar 20, 2021

Duplicate of #10373 (and that itself is a duplicate of an older issue I'm currently unable to find...)

@SimenB SimenB closed this as completed Mar 20, 2021
@github-actions
Copy link

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators May 10, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

2 participants