繁体   English   中英

函数存根不适用于 sinon 和 mocha

[英]Function stub not working with sinon and mocha

我正在尝试为我的测试套件存根函数,但它目前没有按预期工作。 我是使用 mocha 和 sinon 的新手,正在寻找如何使这项工作的方向:

这是正在测试的代码片段,可以在 functions/purchaseOrder.js 中找到。 AccountStatus、creditStatus 和 productStatus 是文件中的本地函数:

var orderHandling=function(clientAccount ,product,inventory,inventoryThreshold,creditCheckMode){

var aStautus=AccountStatus(clientAccount);

var cStatus=creditStatus(clientAccount, creditCheckMode);

var pStatus=productStatus(product,inventory,inventoryThreshold);
...more
}

这就是我试图测试它的方式:

import testFunctions = require('./functions/purchaseOrder.js');
beforeEach(function() {
  stub=sinon.stub(testFunctions, "AccountStatus");
  stub1=sinon.stub(testFunctions, "productStatus");
  stub2=sinon.stub(testFunctions, "creditStatus");  // stub 'calPoints' function
})
it('Initial Test', function() {
  var clientAccount = {
    age: 2,
    balance: 500,
    creditScore: 50
  }
  stub.onCall(0).returns("very good");
  stub1.onCall(0).returns("available");
  stub2.onCall(0).returns("good");

  var creditCheckMode = 'restricted';

  var product = "productname"

  var inventory = [{
    name: "hello",
    productQuantity: 578
  }]

  var inventoryThreshold = 500

  assert.equal(testFunctions.orderHandling(clientAccount, product, inventory, inventoryThreshold, creditCheckMode), "accepted");
});

提前致谢

我已经通过自己的一些挖掘找到了我的问题的答案。 事实证明,我试图删除分配给它引用的匿名函数的变量。 Sinon 无法找到这个匿名函数,因此不会剔除该方法。 为了解决这个问题,我必须将代码更改为: var productStatus = {prodStatus: function() {...}然后像这样删除函数:

var stub = sinon.stub(testFunctions.productStatus, "prodStatus"); 
stub.onCall(0).returns("available");

这完美地工作。 希望这可以帮助某人!

暂无
暂无

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

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