Spies
Loading "Spies (🏁 solution)"
Run locally for transcripts
Let's start by creating a spy for the
logger.log()
method using the vi.spyOn()
function from Vitest:const logger = new Logger()
vi.spyOn(logger, 'log')
const service = new UserService(logger)
The
spyOn()
function has a bit of unusual call signature since it will not accept the logger.log
method reference directly. Instead, it expects the object that owns the method first, and then the method name as a string:vi.spyOn(target, method)
🦉 The reason behind this call signature is how.spyOn()
works under the hood. It redefines themethod
on thetarget
object with a spied version of that method! You can think of it astarget[method] = methodSpy
.
Now that I have the spy ready and recording, I can write an assertion on that method being called with the correct arguments using the
.toHaveBeenCalledWith()
assertion:expect(logger.log).toHaveBeenCalledWith('createUser', { id: 'abc-123' })
Finally, I will make sure that
logger.log()
has been called exactly once:expect(logger.log).toHaveBeenCalledOnce()
To validate the test, I will run
npm test
: ✓ user-service.test.ts (1)
✓ logs out the "createUser" event when creating a new user