Mock functions
Loading "Mock Functions (π solution)"
Run locally for transcripts
In the
emitter.test.ts
, I will start from creating the listener
function but it won't be a regular JavaScript function. Instead, I will use the vi.fn()
API from Vitest, which creates a special kind of function.const listener = vi.fn()
π Learn more aboutvi.fn()
from the Vitest documentation.
Calling
vi.fn()
returns a function imbued with superpowers, one of which is the ability to know when and how it is being called!Note that for this test, I will create an empty mock function because what the listener itself does is irrelevant to the point of the test (asserting that it has been called).
Now that the mock function is ready, I will use it as a listener argument for the
hello
event:emitter.on('hello', listener)
Everything up to this point was the setup for this test. The action here would be calling the
.emit()
method to emit the hello
event because the listeners are only called when the respective event gets emitted.emitter.emit('hello', 'John')
I expect two things to happen once the
hello
event is emitted:- The
listener
function gets called, and gets called once; - The
listener
function gets called with the right dataβthe'John'
string.
The
expect()
function from Vitest comes with handy assertions to describe both of those expectations!First, I will use the
.toHaveBeenCalledOnce()
assertion:expect(listener).toHaveBeenCalledOnce()
This will only pass if the
listener
function has been called exactly once. If it gets called any other number of times, it's a bug, and the test will fail.In the same fashion, I will apply the
.toHaveBeenCalledWith()
assertion to check that the listener
function gets called with the right data:expect(listener).toHaveBeenCalledWith('John')