Skip to content

FAQ

Frequent questions: how to choose spy vs mock, whether to spy on real objects, and how to assert.

Spy or mock?

Use a spy when you want the real behaviour and post-hoc verification; use a mock when the collaboration itself is the contract. If the test asserts "it called save once", a mock is more direct; if it asserts "the user was saved and an email was sent", a spy is more resilient.

Should I spy on the real object or a fake?

Either works. Spying on the real object exercises the actual code path; spying on a fake isolates the unit. Choose based on what the test needs to prove.

How do I assert on a spy?

Inspect the ledger. expect(spy).toHaveBeenCalledWith(...) in Jest; sinon.assert.calledOnceWithExactly(spy, args) in Sinon; verify(spy).method(args) in Mockito. Pick one assertion per intent.

Can a spy replace a mock entirely?

No. A spy has no expectation contract, so it never fails on its own. If you want automatic failure on missing calls, use a mock.