【问题标题】:Function stub not working with sinon and mocha函数存根不适用于 sinon 和 mocha
【发布时间】:2018-11-10 04:05:42
【问题描述】:

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

这是正在测试的代码的 sn-p,可在 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");
});

提前致谢

【问题讨论】:

    标签: javascript mocha.js sinon


    【解决方案1】:

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

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

    这非常有效。希望这对某人有帮助!

    【讨论】:

      猜你喜欢
      • 2020-07-07
      • 1970-01-01
      • 2019-10-13
      • 1970-01-01
      • 2018-06-20
      • 2019-07-27
      • 1970-01-01
      • 2016-02-19
      • 1970-01-01
      相关资源
      最近更新 更多