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

139
Visualizações
How to mock call to constructor of class in 3rd party module called from the same module using jest

I have a 3rd party module like this

class Test {
   async doSomething() {}
}

export const testObject = new Test();  <--- I want to mock this part because constructor requires some input which I don't want to provide as it is not required for tests

another module which imports the above module

import { testObject } from 'module1';

function foo() {
    testObject.doSomething()
}

Now I am trying to write unit tests like below

describe('test', ()=> {
    test('', ()=> {
        foo()
    })
})

new Test() depends on some outside input which I don't want to provide so when i run tests, it fails because of missing input and I am not sure how to stop new Test() from being executed as is and instead a mock functions should be run instead

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Try something like this. If you run this test it'll pass:

Class file.

class SoundPlayer {
  foo: string
  constructor() {
    this.foo = 'bar'
  }

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

export const testObject = new SoundPlayer()

Function file

import { testObject } from './test'

export default function test() {
  testObject.playSoundFile('testing')
}

Test file

import { testObject } from '../test'
import test from '../test1'
jest.mock('../test')

it('should run test', () => {
  test()
  expect(testObject.playSoundFile).toHaveBeenCalledTimes(1)
})

This is a very basic example and there are 4 different ways you can mock. Check out the Jest documentation: https://jestjs.io/docs/es6-class-mocks#the-4-ways-to-create-an-es6-class-mock

about 4 years ago · Juan Pablo Isaza Relatório
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