···2121You should use mock assertions (e.g., [`toHaveBeenCalled`](/api/expect#tohavebeencalled)) on [`expect`](/api/expect) to assert mock results. This API reference describes available properties and methods to manipulate mock behavior.
22222323::: warning IMPORTANT
2424-Vitest spies inherit implementation's `length` property. This means that `length` can be different from the original implementation:
2424+Vitest spies inherit implementation's [`length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length) property when initialized, but it doesn't override it if the implementation was changed later:
25252626-```ts
2626+::: code-group
2727+```ts [vi.fn]
2828+const fn = vi.fn((arg1) => {})
2929+fn.length // == 1
3030+3131+fn.mockImplementation(() => {})
3232+fn.length // == 1
3333+```
3434+```ts [vi.spyOn]
2735const example = {
2836 fn(arg1, arg2) {
2937 // ...
···3442fn.length // == 2
35433644fn.mockImplementation(() => {})
3737-fn.length // == 0
4545+fn.length // == 2
3846```
3947:::
4048
+7-19
packages/spy/src/index.ts
···4848 state,
4949 ...options,
5050 })
5151+ const mockLength = (mockImplementation || originalImplementation)?.length ?? 0
5252+ Object.defineProperty(mock, 'length', {
5353+ writable: true,
5454+ enumerable: false,
5555+ value: mockLength,
5656+ configurable: true,
5757+ })
5158 // inherit the default name so it appears in snapshots and logs
5259 // this is used by `vi.spyOn()` for better debugging.
5360 // when `vi.fn()` is called, we just use the default string
···494501 if (original) {
495502 copyOriginalStaticProperties(namedObject[name], original)
496503 }
497497- let overrideLength: number | undefined
498498- Object.defineProperty(namedObject[name], 'length', {
499499- configurable: true,
500500- get: () => {
501501- if (overrideLength != null) {
502502- return overrideLength
503503- }
504504-505505- const implementation = config.onceMockImplementations[0]
506506- || config.mockImplementation
507507- || prototypeConfig?.onceMockImplementations[0]
508508- || prototypeConfig?.mockImplementation
509509- || original
510510- return implementation?.length ?? 0
511511- },
512512- set: (length: number) => {
513513- overrideLength = length
514514- },
515515- })
516504 return namedObject[name]
517505}
518506