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

146
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
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