Asserting function calls with spies

A spy is a function that records information about every call made to it. For example, instead of assigning an empty function to next, we can assign a spy to it. Whenever next is invoked, information about each invocation is stored inside the spy object. We can then use this information to determine the number of times the spy has been called.

The de facto spy library in the ecosystem is Sinon (sinonjs.org), so let's install it:

$ yarn add sinon --dev

Then, in our unit test, import the spy named export from the sinon package:

import { spy } from 'sinon';

Now, in our test function, instead of assigning an empty function to next, assign it a new spy:

const next = spy();

When the spy function is called, the ...

Get Building Enterprise JavaScript Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.