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 almostprototype methods...
...if you make them prototype methods then funcB
can be mocked:
worker.js
classWorker {
funcA() {
this.funcB();
}
funcB() {
thrownewError('should not make it here');
}
}
module.exports = Worker;
worker.test.js
constWorker = require('./worker');
test('test functionB', () => { /* ... */ })
test('test functionA', () => {
const spy = jest.spyOn(Worker.prototype, 'funcB'); // <= spy on funcB
spy.mockImplementation(() => {}); // <= mock funcBconst work = newWorker();
work.funcA(); // <= call funcAexpect(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:
constWorker = require('./worker')
test('test functionB', () => {...})
test('test functionA', () => {
// You could even just have: const work = require('./worker')const work = newWorker()
work.funcB = jest.fn() //mock funcB
work.funcA() //run funcAexpect(work.funcB).toHaveBeenCalledTimes(1)
})
Post a Comment for "Jest: How To Mock One Specific Function When Using Module.exports"