ES6 Class Mocks

    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.

    We’ll use a contrived example of a class that plays sound files, , and a consumer class which uses that class, SoundPlayerConsumer. We’ll mock SoundPlayer in our tests for SoundPlayerConsumer.

    sound-player.js

    sound-player-consumer.js

    1. import SoundPlayer from './sound-player';
    2. export default class SoundPlayerConsumer {
    3. constructor() {
    4. this.soundPlayer = new SoundPlayer();
    5. }
    6. playSomethingCool() {
    7. const coolSoundFileName = 'song.mp3';
    8. this.soundPlayer.playSoundFile(coolSoundFileName);
    9. }
    10. }

    The 4 ways to create an ES6 class mock

    Calling 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.

    note

    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:

    1. import SoundPlayer from './sound-player';
    2. import SoundPlayerConsumer from './sound-player-consumer';
    3. jest.mock('./sound-player'); // SoundPlayer is now a mock constructor
    4. beforeEach(() => {
    5. // Clear all instances and calls to constructor and all methods:
    6. SoundPlayer.mockClear();
    7. });
    8. it('We can check if the consumer called the class constructor', () => {
    9. const soundPlayerConsumer = new SoundPlayerConsumer();
    10. expect(SoundPlayer).toHaveBeenCalledTimes(1);
    11. });
    12. it('We can check if the consumer called a method on the class instance', () => {
    13. // Show that mockClear() is working:
    14. expect(SoundPlayer).not.toHaveBeenCalled();
    15. const soundPlayerConsumer = new SoundPlayerConsumer();
    16. // Constructor should have been called again:
    17. expect(SoundPlayer).toHaveBeenCalledTimes(1);
    18. const coolSoundFileName = 'song.mp3';
    19. soundPlayerConsumer.playSomethingCool();
    20. // mock.instances is available with automatic mocks:
    21. const mockSoundPlayerInstance = SoundPlayer.mock.instances[0];
    22. const mockPlaySoundFile = mockSoundPlayerInstance.playSoundFile;
    23. expect(mockPlaySoundFile.mock.calls[0][0]).toBe(coolSoundFileName);
    24. // Equivalent to above check:
    25. expect(mockPlaySoundFile).toHaveBeenCalledWith(coolSoundFileName);
    26. expect(mockPlaySoundFile).toHaveBeenCalledTimes(1);
    27. });

    Manual mock

    Create 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.

    __mocks__/sound-player.js

    1. // Import this named export into your test file:
    2. export const mockPlaySoundFile = jest.fn();
    3. const mock = jest.fn().mockImplementation(() => {
    4. return {playSoundFile: mockPlaySoundFile};
    5. });
    6. export default mock;

    Import the mock and the mock method shared by all instances:

    sound-player-consumer.test.js

    1. import SoundPlayer, {mockPlaySoundFile} from './sound-player';
    2. import SoundPlayerConsumer from './sound-player-consumer';
    3. jest.mock('./sound-player'); // SoundPlayer is now a mock constructor
    4. beforeEach(() => {
    5. // Clear all instances and calls to constructor and all methods:
    6. SoundPlayer.mockClear();
    7. mockPlaySoundFile.mockClear();
    8. });
    9. it('We can check if the consumer called the class constructor', () => {
    10. expect(SoundPlayer).toHaveBeenCalledTimes(1);
    11. });
    12. it('We can check if the consumer called a method on the class instance', () => {
    13. const soundPlayerConsumer = new SoundPlayerConsumer();
    14. const coolSoundFileName = 'song.mp3';
    15. soundPlayerConsumer.playSomethingCool();
    16. expect(mockPlaySoundFile).toHaveBeenCalledWith(coolSoundFileName);
    17. });

    Calling jest.mock() with the module factory parameter

    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).

    1. import SoundPlayer from './sound-player';
    2. const mockPlaySoundFile = jest.fn();
    3. jest.mock('./sound-player', () => {
    4. return jest.fn().mockImplementation(() => {
    5. return {playSoundFile: mockPlaySoundFile};
    6. });
    7. });

    Since calls to are hoisted to the top of the file, Jest prevents access to out-of-scope variables. By default, you cannot first define a variable and then use it in the factory. Jest will disable this check for variables that start with the word mock. However, it is still up to you to guarantee that they will be initialized on time. Be aware of .

    For example, the following will throw an out-of-scope error due to the use of fake instead of mock in the variable declaration.

    1. // Note: this will fail
    2. import SoundPlayer from './sound-player';
    3. const fakePlaySoundFile = jest.fn();
    4. jest.mock('./sound-player', () => {
    5. return jest.fn().mockImplementation(() => {
    6. return {playSoundFile: fakePlaySoundFile};
    7. });
    8. });

    The following will throw a ReferenceError despite using mock in the variable declaration, as the mockSoundPlayer is not wrapped in an arrow function and thus accessed before initialization after hoisting.

    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:

    1. import SoundPlayer from './sound-player';
    2. import SoundPlayerConsumer from './sound-player-consumer';
    3. jest.mock('./sound-player');
    4. describe('When SoundPlayer throws an error', () => {
    5. beforeAll(() => {
    6. SoundPlayer.mockImplementation(() => {
    7. return {
    8. playSoundFile: () => {
    9. throw new Error('Test error');
    10. },
    11. };
    12. });
    13. });
    14. it('Should throw an error when calling playSomethingCool', () => {
    15. const soundPlayerConsumer = new SoundPlayerConsumer();
    16. expect(() => soundPlayerConsumer.playSomethingCool()).toThrow();
    17. });
    18. });

    Building 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 class

    If 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:

    __mocks__/sound-player.js

    1. export default class SoundPlayer {
    2. constructor() {
    3. console.log('Mock SoundPlayer: constructor was called');
    4. }
    5. playSoundFile() {
    6. console.log('Mock SoundPlayer: playSoundFile was called');
    7. }
    8. }

    Mock using module factory parameter

    The 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 function

    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).

    1. jest.mock('./sound-player', () => {
    2. return function () {
    3. return {playSoundFile: () => {}};
    4. };
    5. });

    ES6 Class Mocks - 图3note

    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:

    1. jest.mock('./sound-player', () => {
    2. return () => {
    3. // Does not work; arrow functions can't be called with new
    4. return {playSoundFile: () => {}};
    5. };
    6. });

    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.)

    Mocking a specific method of a class

    1. // your jest test file below
    2. import SoundPlayer from './sound-player';
    3. import SoundPlayerConsumer from './sound-player-consumer';
    4. const playSoundFileMock = jest
    5. .spyOn(SoundPlayer.prototype, 'playSoundFile')
    6. .mockImplementation(() => {
    7. console.log('mocked function');
    8. }); // comment this line if just want to "spy"
    9. it('player consumer plays music', () => {
    10. const player = new SoundPlayerConsumer();
    11. player.playSomethingCool();
    12. expect(playSoundFileMock).toHaveBeenCalled();
    13. });

    Lets imagine our class SoundPlayer has a getter method foo and a static method brand

    1. export default class SoundPlayer {
    2. this.foo = 'bar';
    3. playSoundFile(fileName) {
    4. console.log('Playing sound file ' + fileName);
    5. }
    6. get foo() {
    7. return 'bar';
    8. }
    9. static brand() {
    10. return 'player-brand';
    11. }
    12. }

    You can mock/spy on them easily, here is an example:

    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 constructor

    In order to track calls to the constructor, replace the function returned by the HOF with a Jest mock function. Create it with , and then specify its implementation with mockImplementation().

    1. import SoundPlayer from './sound-player';
    2. jest.mock('./sound-player', () => {
    3. // Works and lets you check for constructor calls:
    4. return jest.fn().mockImplementation(() => {
    5. return {playSoundFile: () => {}};
    6. });
    7. });

    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).toBeGreaterThan(0);

    Mocking non-default class exports

    If 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.

    1. import {SoundPlayer} from './sound-player';
    2. jest.mock('./sound-player', () => {
    3. // Works and lets you check for constructor calls:
    4. return {
    5. SoundPlayer: jest.fn().mockImplementation(() => {
    6. return {playSoundFile: () => {}};
    7. }),
    8. };
    9. });

    Our 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.

    1. import SoundPlayer from './sound-player';
    2. const mockPlaySoundFile = jest.fn();
    3. jest.mock('./sound-player', () => {
    4. return jest.fn().mockImplementation(() => {
    5. return {playSoundFile: mockPlaySoundFile};
    6. // Now we can track calls to playSoundFile
    7. });
    8. });

    The manual mock equivalent of this would be:

    __mocks__/sound-player.js

    1. // Import this named export into your test file
    2. export const mockPlaySoundFile = jest.fn();
    3. const mock = jest.fn().mockImplementation(() => {
    4. return {playSoundFile: mockPlaySoundFile};
    5. });
    6. export default mock;

    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 tests

    To clear the record of calls to the mock constructor function and its methods, we call in the beforeEach() function:

    1. beforeEach(() => {
    2. SoundPlayer.mockClear();
    3. mockPlaySoundFile.mockClear();
    4. });

    Complete example

    Here’s a complete test file which uses the module factory parameter to jest.mock:

    sound-player-consumer.test.js

    1. import SoundPlayer from './sound-player';
    2. import SoundPlayerConsumer from './sound-player-consumer';
    3. const mockPlaySoundFile = jest.fn();
    4. jest.mock('./sound-player', () => {
    5. return jest.fn().mockImplementation(() => {
    6. return {playSoundFile: mockPlaySoundFile};
    7. });
    8. });
    9. beforeEach(() => {
    10. SoundPlayer.mockClear();
    11. mockPlaySoundFile.mockClear();
    12. });
    13. it('The consumer should be able to call new() on SoundPlayer', () => {
    14. const soundPlayerConsumer = new SoundPlayerConsumer();
    15. // Ensure constructor created the object:
    16. expect(soundPlayerConsumer).toBeTruthy();
    17. });
    18. it('We can check if the consumer called the class constructor', () => {
    19. const soundPlayerConsumer = new SoundPlayerConsumer();
    20. expect(SoundPlayer).toHaveBeenCalledTimes(1);
    21. });
    22. it('We can check if the consumer called a method on the class instance', () => {
    23. const soundPlayerConsumer = new SoundPlayerConsumer();
    24. const coolSoundFileName = 'song.mp3';
    25. soundPlayerConsumer.playSomethingCool();
    26. expect(mockPlaySoundFile.mock.calls[0][0]).toBe(coolSoundFileName);