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