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

138
Views
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 answers
Answer question

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 Report
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!