# Multiple calls to Jest mock returns last call props for all calls

- URL: https://www.heissenberger.at/en/blog/jest-mock-wrong-props-value/
- Language: en
- Published: 2023-04-18
- Tags: Jest, Vitest, Javascript, Testing, Mock, FixIt

> Insights to the problem and a solution to fix your tests in Jest and Vitest

In JavaScript, when you pass an object as an argument to a function, the function receives a reference to the original object in memory, rather than a copy of the object. This means that any changes made to the object within the function will affect the original object outside of the function as well.

This behavior can sometimes lead to unexpected results when using Jest's or Vitest mocking features, particularly when examining the `mock.calls` array. In this blog post, we will explore why `mock.calls` holds references to actual values when a function is called twice with an object argument.

Let's start with an example to demonstrate this behavior. Suppose we have a function called `getUserByID` that takes an object representing a user and gets some data from a database. We want to test this function using Jest's mocking features to ensure that it is working as expected. Here's our initial test:

```javascript
class UserList {
  constructor(getUserByID) {
    this.getUserByID = getUserByID
  }
  getAll() {
    let indexPara = { id: undefined }
    this.getUserByID(indexPara)
  }
}

it("mockCalls", async () => {
  const getUserByID = vi.fn()

  const ul = new UserList(getUserByID)
  getUserByID.mockImplementation(props => {
    Promise.resolve(`User ${props.id}`)
  })

  ul.getAll()

  expect(getUserByID).toHaveBeenCalledTimes(1)
  // equal to: expect(getUserByID.mock.calls).toEqual([[{id:0}]])
  expect(getUserByID).toHaveBeenNthCalledWith(1, { id: 0 })
})
```

In this test, we create a mock of the function using Jest's `jest.fn()` method and pass it to the contructor of the `UserList` class . We then use Jest's `toHaveBeenNthCalledWith()` and `toHaveBeenCalledTimes()` matchers to ensure that the `getUserByID` function was called once with the correct object with the user id.

Now, suppose we want to modify this test to call `getUserByID` twice with different user id. We might expect that the `mock.calls` array would hold references to two separate user objects, one for each call. However, let's see what actually happens when we run the modified test:

```javascript
class UserList {
  constructor(getUserByID) {
    this.getUserByID = getUserByID
  }
  getAll() {
    let indexPara = { id: 1 }
    this.getUserByID(indexPara)
    indexPara.id = 2
    this.getUserByID(indexPara)
  }
}

it("mockCalls", async () => {
  const getUserByID = vi.fn()

  const ul = new UserList(getUserByID)
  getUserByID.mockImplementation(props => {
    Promise.resolve(`User ${props.id}`)
  })

  ul.getAll()

  expect(getUserByID).toHaveBeenCalledTimes(2)
  // equal to: expect(getUserByID.mock.calls).toEqual([[{id:0}],[{id:1}]])
  expect(getUserByID).toHaveBeenNthCalledWith(1, { id: 1 }) // AssertionError: expected 1st "spy" call to have been called with [ { id: +1 } ]
  expect(getUserByID).toHaveBeenNthCalledWith(2, { id: 2 })
})
```

In this test, we call `getUserByID` twice with two different user objects, `{id:1}` and `{id:2}`. We then use Jest's `toHaveBeenNthCalledWith()` and `toHaveBeenCalledTimes()` matchers to ensure that `updateUser` was called twice with the correct arguments. Finally, we examine the `mock.calls` array to compare the user objects passed to each call.

`AssertionError: expected 1st "spy" call to have been called with [ { id: +1 } ]`

Expected: `[ [ {id: 0} ], [ {id: 1} ] ]`
Received: `[ [ {id: 1} ], [ {id: 1} ] ]`

What we find is that the `mock.calls` array holds references to the actual user objects passed to the function, rather than copies of the objects. This means that the two elements in the `mock.calls` array are references to the same object in memory, rather than two separate objects with identical values. Which in all cases leads to a result which returns object passed to the last call for all calls.

This behavior can be surprising at first, especially if you are used to working with primitive types like strings or numbers, which are passed by value rather than by reference. However, it is important to keep in mind when working with Jest's mocking features.

To work around this behavior and ensure that `mock.calls` holds separate objects for each call, you can create copies of the objects before passing them to the function, like so:

There are two ways to fix the problem:

1. avoid to call function with object references
2. modify your test code to capture the function calls

> To be clear - the code we tested is working and not broken in any way! It is our test which fails to capture the bits we need to test the code.

## Change the application code

The part in the code which breaks the test is here:

```javascript
getAll() {
        let indexPara = { id: 1 }
        this.getUserByID(indexPara) // passing a reference to the object
        indexPara.id = 2 // modifying
        this.getUserByID(indexPara) // passing the same reference
    }
```

In the code we pass the reference of the object to our mocked function.

One of many solutions is to copy the object to create a new object:

```javascript
getAll() {
        let indexPara = { id: 1 }
        this.getUserByID({...indexPara}) // passing a reference to the object
        indexPara.id = 2 // modifying
        this.getUserByID({...indexPara}) // passing the same reference
    }
```

> Many time we do not want to change our code to fix problems in the tests and in some cases the part you mock is called by an external library.

## Fix the problem in your tests

```javascript
it("mockCalls", async () => {
  const getUserByID = vi.fn()

  const ul = new UserList(getUserByID)
  let mockCalls = [] // 1. create a store for the call history
  getUserByID.mockImplementation(props => {
    mockCalls.push(props) // 2. push the props to the history
    Promise.resolve(`User ${props.id}`)
  })

  ul.getAll()

  expect(getUserByID).toHaveBeenCalledTimes(2)
  // replace with your own call history
  expect(mockCalls).toEqual([{ id: 1 }, { id: 2 }])
  //expect(getUserByID).toHaveBeenNthCalledWith(1, { id: 1 })
  //expect(getUserByID).toHaveBeenNthCalledWith(2, { id: 2 })
})
```

1. `let mockCalls=[]` - create a store for the call history
2. `mockCalls.push(props)` - push the props to the history
3. `expect(mockCalls).toEqual([{ id: 1 },{ id: 2 }])` - validate the call history

References:

- [Jest Github Issue Discussion](https://github.com/facebook/jest/issues/434)
- [Vitest Mocking](https://vitest.dev/guide/mocking.html)
