It is a function that allows you to override the function that was called and change the implementation of it for testing purposes. It can be useful for checking how often function was triggered as well. it is useful when you want to avoid function being triggered more than once.

const apples = 0  
const cart = {  
	getApples: () => 13  
}  
  
test("", () => {  
	const spy = vi.spyOn(card, "getApples")  
	// The below overrides the returned value of `getApples` method  
	spy.mockImplementation(() => apples)  
  
	apples = 1  
  
	expect(cart.getApples()).toBe(1)  
	expect(cart.getApples()).toHaveBeencalledTimes(1)  
  
	// Here, it is restoring the original returned value of a function  
	spy.mockRestore()  
	expect(cart.getApples()).toBe(13)  
})  

Spy and Typescript

If you want to make sure that you satisfy typescript when using spies, you can use SpyInstance<Parameters<typeof functionName>>