Jest: How To Mock One Specific Function When Using Module.exports
I'm trying to mock one specific function when using module.exports. How could I test the inner function B? In my worker.js module.exports = function () { this.funcA = funcA th
Solution 1:
There isn't a way to mock funcB
the way the code is currently written since funcA
calls funcB
directly.
The easiest way to fix it is to note that worker.js
returns a constructor function and funcA
and funcB
are almost prototype methods...
...if you make them prototype methods then funcB
can be mocked:
worker.js
class Worker {
funcA() {
this.funcB();
}
funcB() {
throw new Error('should not make it here');
}
}
module.exports = Worker;
worker.test.js
const Worker = require('./worker');
test('test functionB', () => { /* ... */ })
test('test functionA', () => {
const spy = jest.spyOn(Worker.prototype, 'funcB'); // <= spy on funcB
spy.mockImplementation(() => {}); // <= mock funcB
const work = new Worker();
work.funcA(); // <= call funcA
expect(spy).toHaveBeenCalledTimes(1); // Success!
spy.mockRestore(); // <= restore funcB
})
Solution 2:
I know this is an old question but I thought I would chime in as I was searching for a way to do this as well and have discovered it is in fact possible.
Rather than calling the javascript function as above, you'll need to give it the scope of this
to ensure that when you mock funcB
, funcA
calls the mocked version rather than just the function itself.
This means worker.js
becomes
module.exports = function () {
this.funcA = funcA
this.funcB = funcB
}
funcA () {
this.funcB()
}
funcB() {/* Your impl */}
And worker.test.js
can remain, as before:
const Worker = require('./worker')
test('test functionB', () => {...})
test('test functionA', () => {
// You could even just have: const work = require('./worker')
const work = new Worker()
work.funcB = jest.fn() //mock funcB
work.funcA() //run funcA
expect(work.funcB).toHaveBeenCalledTimes(1)
})
Post a Comment for "Jest: How To Mock One Specific Function When Using Module.exports"