1

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!

AntonSack
  • 1,021
  • 2
  • 25
  • 47
  • This is the way to go if you do want to test the code w/o changing. Alternatively you could make your code more unit testable by allowing dependency injection `function a(B = classB) { const b = new B(); ...}` – Yury Tarabanko Jul 29 '20 at 18:12

1 Answers1

1

You are doing right. Use the rewire package, set a mocked classB object. 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, the classB with mocked methodA may cause other tests to fail.

The better way is to use dependency injection. Creating a mocked classB object for each test case and pass it into a function like this:

function a(b) {
  b.methodA();
}

// test file
const b = { 
  methodA() {
    console.log('stubbed methodA');
  } 
}
a(b);

This can better ensure the isolation of test double between test cases.

Lin Du
  • 88,126
  • 95
  • 281
  • 483