ES6 Class Mocks
Jest can be used to mock ES6 classes that are imported into files you want to test.
ES6 classes are constructor functions with some syntactic sugar. Therefore, any mock for an ES6 class must be a function or an actual ES6 class (which is, again, another function). So you can mock them using mock functions.
#
An ES6 Class ExampleWe'll use a contrived example of a class that plays sound files, SoundPlayer
, and a consumer class which uses that class, SoundPlayerConsumer
. We'll mock SoundPlayer
in our tests for SoundPlayerConsumer
.
#
The 4 ways to create an ES6 class mock#
Automatic mockCalling jest.mock('./sound-player')
returns a useful "automatic mock" you can use to spy on calls to the class constructor and all of its methods. It replaces the ES6 class with a mock constructor, and replaces all of its methods with mock functions that always return undefined
. Method calls are saved in theAutomaticMock.mock.instances[index].methodName.mock.calls
.
Please note that if you use arrow functions in your classes, they will not be part of the mock. The reason for that is that arrow functions are not present on the object's prototype, they are merely properties holding a reference to a function.
If you don't need to replace the implementation of the class, this is the easiest option to set up. For example:
#
Manual mockCreate a manual mock by saving a mock implementation in the __mocks__
folder. This allows you to specify the implementation, and it can be used across test files.
Import the mock and the mock method shared by all instances:
jest.mock()
with the module factory parameter#
Calling jest.mock(path, moduleFactory)
takes a module factory argument. A module factory is a function that returns the mock.
In order to mock a constructor function, the module factory must return a constructor function. In other words, the module factory must be a function that returns a function - a higher-order function (HOF).
A limitation with the factory parameter is that, since calls to jest.mock()
are hoisted to the top of the file, it's not possible to first define a variable and then use it in the factory. An exception is made for variables that start with the word 'mock'. It's up to you to guarantee that they will be initialized on time! For example, the following will throw an out-of-scope error due to the use of 'fake' instead of 'mock' in the variable declaration:
mockImplementation()
or mockImplementationOnce()
#
Replacing the mock using You can replace all of the above mocks in order to change the implementation, for a single test or all tests, by calling mockImplementation()
on the existing mock.
Calls to jest.mock are hoisted to the top of the code. You can specify a mock later, e.g. in beforeAll()
, by calling mockImplementation()
(or mockImplementationOnce()
) on the existing mock instead of using the factory parameter. This also allows you to change the mock between tests, if needed:
#
In depth: Understanding mock constructor functionsBuilding your constructor function mock using jest.fn().mockImplementation()
makes mocks appear more complicated than they really are. This section shows how you can create your own mocks to illustrate how mocking works.
#
Manual mock that is another ES6 classIf you define an ES6 class using the same filename as the mocked class in the __mocks__
folder, it will serve as the mock. This class will be used in place of the real class. This allows you to inject a test implementation for the class, but does not provide a way to spy on calls.
For the contrived example, the mock might look like this:
#
Mock using module factory parameterThe module factory function passed to jest.mock(path, moduleFactory)
can be a HOF that returns a function*. This will allow calling new
on the mock. Again, this allows you to inject different behavior for testing, but does not provide a way to spy on calls.
#
* Module factory function must return a functionIn order to mock a constructor function, the module factory must return a constructor function. In other words, the module factory must be a function that returns a function - a higher-order function (HOF).
Note: Arrow functions won't work
Note that the mock can't be an arrow function because calling new
on an arrow function is not allowed in JavaScript. So this won't work:
This will throw TypeError: _soundPlayer2.default is not a constructor, unless the code is transpiled to ES5, e.g. by @babel/preset-env
. (ES5 doesn't have arrow functions nor classes, so both will be transpiled to plain functions.)
#
Keeping track of usage (spying on the mock)Injecting a test implementation is helpful, but you will probably also want to test whether the class constructor and methods are called with the correct parameters.
#
Spying on the constructorIn order to track calls to the constructor, replace the function returned by the HOF with a Jest mock function. Create it with jest.fn()
, and then specify its implementation with mockImplementation()
.
This will let us inspect usage of our mocked class, using SoundPlayer.mock.calls
: expect(SoundPlayer).toHaveBeenCalled();
or near-equivalent: expect(SoundPlayer.mock.calls.length).toEqual(1);
#
Mocking non-default class exportsIf the class is not the default export from the module then you need to return an object with the key that is the same as the class export name.
#
Spying on methods of our classOur mocked class will need to provide any member functions (playSoundFile
in the example) that will be called during our tests, or else we'll get an error for calling a function that doesn't exist. But we'll probably want to also spy on calls to those methods, to ensure that they were called with the expected parameters.
A new object will be created each time the mock constructor function is called during tests. To spy on method calls in all of these objects, we populate playSoundFile
with another mock function, and store a reference to that same mock function in our test file, so it's available during tests.
The manual mock equivalent of this would be:
Usage is similar to the module factory function, except that you can omit the second argument from jest.mock()
, and you must import the mocked method into your test file, since it is no longer defined there. Use the original module path for this; don't include __mocks__
.
#
Cleaning up between testsTo clear the record of calls to the mock constructor function and its methods, we call mockClear()
in the beforeEach()
function:
#
Complete exampleHere's a complete test file which uses the module factory parameter to jest.mock
: