Jest Mocks and Spies
Learn how to use Jest mocks and spies to test that functions are called with the correct arguments.
We'll cover the following...
When testing our code, we often want to ensure that a particular function was called or that it was called with the correct parameters. This is most often seen when a particular function calls other functions in a sequence in order to execute some business logic.
We may call an initialize
function, for example, and this initialize
function may call a number of REST services to load data.
When writing a test for our initialize
function, we would want to ensure that all of the calls to REST services were called. To ensure that functions are called, we use Jest mocks or Jest spies.
Jest mocks
As an example of where we can use a Jest mock, consider the following class:
class MyCallbackClass {executeCallback(value: string, callbackFn: (value: string) => null) {console.log(`executeCallback invoking callbackFn`);callbackFn(value);}}
Here, we have a class named MyCallbackClass
, which has a single method named executeCallback
on line 2. The executeCallback
function accepts two parameters:
- The first parameter is
value
of typestring
. - The second parameter is
callbackFn
, which is a function that has a single parameter named value of typestring
.
The executeCallback
method logs a value to the console and then invokes the callback function that was passed in, along with the string value that was passed in.
Let’s take a look at how we can use a Jest mock function to use as the callbackFn
argument:
it("should mock callback function", () => {let mock = jest.fn();let myCallbackClass = new MyCallbackClass();myCallbackClass.executeCallback("test", mock);expect(mock).toHaveBeenCalled();});
-
We start our test by creating a variable named
mock
on line 2 that is assigned to the result of ...