I need to write an unit test for the following classA. I do not want to test methodA but set a dummy method instead:
const classB = require('classB');
function a() {
const b = classB();
b.methodA();
}
I tried to use rewire:
const classA = rewire('classA');
const classBMock = require('classB');
classBMock.prototype.methodA = function() {
}
classA.__set__('classB', classBMock);
classA.a();
Is there a better way to achieve my goal?
Thanks!
You are doing right. Use the
rewirepackage, set a mockedclassBobject. But it is not recommended to override the method on the prototype with a mocked one. You have to restore it to the original one after executing the test case. Otherwise, theclassBwith mockedmethodAmay cause other tests to fail.The better way is to use dependency injection. Creating a mocked
classBobject for each test case and pass it intoafunction like this:This can better ensure the isolation of test double between test cases.