Mock

A fake dependency carrying expectations about how it must be used, so the test fails unless sendEmail was called once, with this.

pretend version of the APIfake it so it doesn't call Stripemock the APImoking the network in testsrequire this dependency to be called with these argumentsset expectations on a fake and verify themfake the third party servicemy test should fail if sendEmail never runs

See it

Live demo coming soon

What it is

In the strict taxonomy (Gerard Meszaros, popularized by Martin Fowler) a mock is a stand-in that carries expectations: you state up front which calls it must receive, and the double itself fails the test when reality does not match. That is behavior verification, as opposed to checking a returned value. Mockito in Java and Python's 'unittest.mock' are the clearest examples.

Framework vocabulary in JavaScript is looser, so it is worth naming the gap. 'vi.fn()' and 'jest.fn()' hand you a callable that returns what you configure and records every call; you supply the expectation afterward with 'toHaveBeenCalledWith'. Same intent, different moment. A spy is the neighboring idea: it wraps the real function and records calls without replacing what it does.

Reach for a mock when the thing you care about is the side effect and there is nothing to inspect afterward. Did the checkout publish an 'order.created' event? Did the retry actually fire three times? Did the logger record the failure? None of that shows up in a return value, so the call record is your only evidence.

The cost is coupling. A mock encodes how your code talks to its collaborator, so renaming a method or reordering two calls turns tests red even though behavior never changed. Mock the boundary you own, meaning one wrapper you wrote around the SDK or the client interface you inject, rather than every internal function. And note that casual speech calls every double a mock: if you never assert on the calls, what you actually built is a stub, MSW handlers very much included.

Ask AI for it

Add mocks to these tests for the side-effect collaborators (email, analytics, webhook dispatch). Inject each one as a vi.fn() mock rather than reaching into the module, configure only the return values this scenario needs, and then verify the expected interaction: toHaveBeenCalledTimes for the count and toHaveBeenCalledWith for the arguments, including the case where a call must not happen at all. Reset all mocks in beforeEach so counts never leak between tests, and add one case where the mocked call rejects so the error path is covered. Use the word stub, not mock, for any HTTP handler that only returns a canned response and is never asserted on.

You might have meant

stubspytest doubleunit testintegration test

Go deeper