My SUT (SoundPlayerConsumer class) creates multiple instances of a class that I need to mock (SoundPlayer). How can I mock this SoundPlayer class so that it returns a deterministic object each time it's called?
For example, my classes:
// sound-player.js
module.exports = class SoundPlayer {
constructor(sound) {
this.sound = sound;
}
playSound() {
console.log(`Playing ${sound}`);
}
}
// sound-player-consumer.js
module.exports = class SoundPlayerConsumer {
constructor(soundPlayer) {
this.helloSound = new SoundPlayer('hello');
this.goodbyeSounnd = new SoundPlayer('goodbye');
}
playSounds() {
this.helloSound.playSound();
this.goodbyeSounnd.playSound();
}
}
What I'm trying to achieve (something along these lines):
// sound-player-consumer.test.js
const mockHelloPlayer = { playSound: jest.fn() };
const mockGoodbyePlayer = { playSound: jest.fn() };
jest.mock('./sound-player', () => {
return jest.fn() // constructor function
.mockReturnValueOnce(mockHelloPlayer) // first returns the hello player
.mockReturnValueOnce(mockGoodbyePlayer); // then returns the goodbye player
});
test('hello then goodbye', () => {
const consumer = new SoundPlayerConsumer();
consumer.playSounds();
expect(mockHelloPlayer.playSound).toBeCalled();
expect(mockGoodbyePlayer.playSound).toBeCalled();
expect(mockHelloPlayer.playSound.mock.invocationCallOrder[0])
.toBeLessThan(mockGoodbyePlayer.playSound.mock.invocationCallOrder[0]);
});
This test throws an error:
TypeError: this.helloSound.playSound is not a function
I've read over the docs several times and still dont fully understand the module-factory approach - but this error is something to do with my mock objects "not wrapped in an arrow function and thus accessed before initialization after hoisting"
I'm sure there's something really obvious I'm missing here. Any help appreciated!