3

Please help me! I have been wrecking my mind but I can not find out how should I stub a variable! Am I wrong? Should I use Spy?

How should I test this code

module.exports = async () => {
  var variable = 'something';
  var taskProcessor = require('taskprocessor');
  try {
    taskProcessor(variable).then().catch();
    //blah blah 
    //blah blah
    //blah blah
    //blah blah
  } catch (error) {
    console.log(err);
  }
};
george
  • 33
  • 3
  • 1
    Welcome to SO! If this variable is purely local to the function, what's the point in stubbing it? Typically you only spy on/mock/stub non-implementation details like parameters and library dependencies invoked by the function you're unit testing. – ggorlen Apr 22 '21 at 17:50
  • 1
    also, it not the way you handle error, console.log(err) will never be reached if you have put it there only for the sake of taskProcessor – Robot Apr 22 '21 at 18:20

1 Answers1

3

First of all, you should know what is stub or spy (I excluded mocks intentionally)

We use doubles to Control a method’s behavior, then change the test direction to cover all paths in our test.

The spy wraps around the function, it does not replace its functionality! But with stub we can define the output. Spy is literally sending an spy inside your enemies (in this case your code :D) to mimic the behavior of a genuine entity and gather information for you!

now let’s go back to your question!

You can use rewire module in this case. From it’s git page

rewire adds a special setter and getter to modules so you can modify their behavior for better unit testing. You may

  • inject mocks for other modules or globals like process
  • inspect private variables
  • override variables within the module.

So you can set any variable like this: enter image description here

Robot
  • 913
  • 6
  • 8