ES6 Class Mocks·续1

In depth: Understanding mock constructor functions

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. 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. 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.jsexport default class SoundPlayer {  constructor() {    console.log('Mock SoundPlayer: constructor was called');  }  playSoundFile() {    console.log('Mock SoundPlayer: playSoundFile was called');  }}

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). In other words, the module factory must be a function that returns a function - a higher-order function (HOF).

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

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: So this won’t work:

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

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

In 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(). Create it with jest.fn(), and then specify its implementation with mockImplementation().

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

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

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

Spying on methods of our class

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

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

The manual mock equivalent of this would be:

// __mocks__/sound-player.js// Import this named export into your test fileexport const mockPlaySoundFile = jest.fn();const mock = jest.fn().mockImplementation(() => {  return {playSoundFile: mockPlaySoundFile};});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. 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 mockClear() in the beforeEach() function:

beforeEach(() => {  SoundPlayer.mockClear();  mockPlaySoundFile.mockClear();});

Complete example

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

// sound-player-consumer.test.jsimport SoundPlayer from './sound-player';import SoundPlayerConsumer from './sound-player-consumer';const mockPlaySoundFile = jest.fn();jest.mock('./sound-player', () => {  return jest.fn().mockImplementation(() => {    return {playSoundFile: mockPlaySoundFile};  });});beforeEach(() => {  SoundPlayer.mockClear();  mockPlaySoundFile.mockClear();});it('The consumer should be able to call new() on SoundPlayer', () => {  const soundPlayerConsumer = new SoundPlayerConsumer();  // Ensure constructor created the object:  expect(soundPlayerConsumer).toBeTruthy();});it('We can check if the consumer called the class constructor', () => {  const soundPlayerConsumer = new SoundPlayerConsumer();  expect(SoundPlayer).toHaveBeenCalledTimes(1);});it('We can check if the consumer called a method on the class instance', () => {  const soundPlayerConsumer = new SoundPlayerConsumer();  const coolSoundFileName = 'song.mp3';  soundPlayerConsumer.playSomethingCool();  expect(mockPlaySoundFile.mock.calls[0][0]).toEqual(coolSoundFileName);});