简体   繁体   English

如何在 node.js 中监视定义的变量

[英]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);
  }
};

First of all, you should know what is stub or spy (I excluded mocks intentionally)首先,你应该知道什么是 stub 或 spy(我故意排除了 mocks)

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.间谍包裹在 function 周围,它不会取代它的功能。 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!但是使用存根,我们可以定义 output:间谍实际上是在你的敌人内部发送一个间谍(在这种情况下是你的代码:D),以模仿真实实体的行为并为你收集信息!

now let's go back to your question!现在让我们 go 回到您的问题!

You can use rewire module in this case.在这种情况下,您可以使用 rewire 模块。 From it's git page从它的 git 页面

rewire adds a special setter and getter to modules so you can modify their behavior for better unit testing. rewire 为模块添加了一个特殊的 setter 和 getter,因此您可以修改它们的行为以进行更好的单元测试。 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:所以你可以像这样设置任何变量: 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM