Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

102
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda