Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how spy a defined variable in node.js

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);
  }
};
like image 311
george Avatar asked Jul 13 '26 15:07

george


1 Answers

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

like image 165
Robot Avatar answered Jul 16 '26 05:07

Robot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!