Fredmental
Fredmental

Reputation: 565

How do you mock an instance/class variable on a es6 class in jest?

The docs for es6 class mocks in jest show this example:

export default class SoundPlayer {
  constructor() {
    this.foo = 'bar';
  }

  playSoundFile(fileName) {
    console.log('Playing sound file ' + fileName);
  }
}

But the docs show only mocking playSoundFile. How would you mock and access this.foo? I'm trying to use .spyOn with mockImplementation but that only works for functions. I also only want to mock the this.foo instance variable, not the playSoundFile method as I want to call the method as it is in the class, with it not being mocked.

Link to docs: https://jestjs.io/docs/en/es6-class-mocks

Upvotes: 1

Views: 3140

Answers (1)

Ahsan Kamal
Ahsan Kamal

Reputation: 51

You can use manual mocks as shown in the jest documentation. You can mock the properties/instance variables as shown in the example below. You just need to add properties with their mocked values in the return statement. This is how i did it. There might be other ways as well.

// __mocks__/sound-player.js

// Import this named export into your test file:
export const mockPlaySoundFile = jest.fn();
const mock = jest.fn().mockImplementation(() => {
  return {
    foo: 'bar',
    playSoundFile: mockPlaySoundFile
  };
});

export default mock;

Upvotes: 0

Related Questions