[Vitest] mockClear, mockReset, mockRestore

mockClear

Clears all information about every call. After calling it, all properties on .mock will return to their initial state. This method does not reset

const person = {
  greet: (name: string) => `Hello ${name}`,
}
const spy = vi.spyOn(person, 'greet').mockImplementation(() => 'mocked')
expect(person.greet('Alice')).toBe('mocked')
expect(spy.mock.calls).toEqual([['Alice']])
expect(spy).toHaveBeenCalledOnce()

// clear call history but keep mock implementation
spy.mockClear()
expect(spy.mock.calls).toEqual([])
expect(person.greet('Bob')).toBe('mocked')
expect(spy.mock.calls).toEqual([['Bob']])
expect(spy).toHaveBeenCalledOnce()

As if the spy never called previously

 

mockReset

Does what mockClear does and resets the mock implementation. This also resets all "once" implementations.

Note that resetting a mock from vi.fn() will set the implementation to an empty function that returns undefined. Resetting a mock from vi.fn(impl) will reset the implementation to impl.

This is useful when you want to reset a mock to its original state.

const person = {
  greet: (name: string) => `Hello ${name}`,
}
const spy = vi.spyOn(person, 'greet').mockImplementation(() => 'mocked')
expect(person.greet('Alice')).toBe('mocked')
expect(spy.mock.calls).toEqual([['Alice']])

// clear call history and reset implementation, but method is still spied
spy.mockReset()
expect(spy.mock.calls).toEqual([])
expect(person.greet).toBe(spy)
expect(person.greet('Bob')).toBe('Hello Bob')
expect(spy.mock.calls).toEqual([['Bob']])

As if we never configure the spy implementation or return value

 

mockRestore

Does what mockReset does and restores the original descriptors of spied-on objects, if the mock was created with vi.spyOn.

mockRestore on a vi.fn() mock is identical to mockReset.

const person = {
  greet: (name: string) => `Hello ${name}`,
}
const spy = vi.spyOn(person, 'greet').mockImplementation(() => 'mocked')
expect(person.greet('Alice')).toBe('mocked')
expect(spy.mock.calls).toEqual([['Alice']])

// clear call history and restore spied object method
spy.mockRestore()
expect(spy.mock.calls).toEqual([])
expect(person.greet).not.toBe(spy)
expect(person.greet('Bob')).toBe('Hello Bob')
expect(spy.mock.calls).toEqual([])

As if we first initlize spy with no extra confguration

 

Resetting Mocks and Spies Between Tests

beforeEach(() => {
  vi.clearAllMocks()
  vi.resetAllMocks()
  vi.restoreAllMocks()
})


// or global
defineConfig({
  test: {
    ...
    restoreMocks: true,
    clearMocks: true,
    mockReset: true
  }
})

 

posted @ 2026-03-01 19:56  Zhentiw  阅读(1)  评论(0)    收藏  举报