Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

109
Views
Mock ES6 class to create a sequence of deterministic instances

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!

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!