Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

103
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda