Skip to content

Commit 61703c9

Browse files
authored
docs: mention that arguments are not cloned (#8385)
1 parent 010fc55 commit 61703c9

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

docs/api/mock.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -371,6 +371,37 @@ fn.mock.calls === [
371371
]
372372
```
373373

374+
:::warning Objects are Stored by Reference
375+
Note that Vitest always stores objects by reference in all properies of the `mock` state. This means that if the properties were changed by your code, then some assertions like [`.toHaveBeenCalledWith`](/api/expect#tohavebeencalledwith) will not pass:
376+
377+
```ts
378+
const argument = {
379+
value: 0,
380+
}
381+
const fn = vi.fn()
382+
fn(argument) // { value: 0 }
383+
384+
argument.value = 10
385+
386+
expect(fn).toHaveBeenCalledWith({ value: 0 }) // [!code --]
387+
388+
// The equality check is done against the original argument,
389+
// but its property was changed between the call and assertion
390+
expect(fn).toHaveBeenCalledWith({ value: 10 }) // [!code ++]
391+
```
392+
393+
In this case you can clone the argument yourself:
394+
395+
```ts{6}
396+
const calledArguments = []
397+
const fn = vi.fn((arg) => {
398+
calledArguments.push(structuredClone(arg))
399+
})
400+
401+
expect(calledArguments[0]).toEqual({ value: 0 })
402+
```
403+
:::
404+
374405
## mock.lastCall
375406

376407
```ts

0 commit comments

Comments
 (0)