简体   繁体   English

函数存根不适用于 sinon 和 mocha

[英]Function stub not working with sinon and mocha

I am trying to stub functions for my test suite and it is currently not working as expected.我正在尝试为我的测试套件存根函数,但它目前没有按预期工作。 I am new to using mocha and sinon and am looking for direction in how to make this work:我是使用 mocha 和 sinon 的新手,正在寻找如何使这项工作的方向:

Here is a snippet of the code that is being tested which is found in functions/purchaseOrder.js.这是正在测试的代码片段,可以在 functions/purchaseOrder.js 中找到。 The AccountStatus, creditStatus and productStatus are local functions within the file: 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
}

and this is how I am trying to test it:这就是我试图测试它的方式:

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");
});

Thanks in advance提前致谢

I have figured out the answer to my question through some digging myself.我已经通过自己的一些挖掘找到了我的问题的答案。 It turns out that I am trying to stub out the variable that is assigned to the anonymous function it is referencing.事实证明,我试图删除分配给它引用的匿名函数的变量。 Sinon is unable to find this anonymous function and therefore is not stubbing out the method. Sinon 无法找到这个匿名函数,因此不会剔除该方法。 To fix this I had to change the code to be: var productStatus = {prodStatus: function() {...} and then stub out the functions like so:为了解决这个问题,我必须将代码更改为: var productStatus = {prodStatus: function() {...}然后像这样删除函数:

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

This works perfectly.这完美地工作。 Hope this helps someone!希望这可以帮助某人!

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

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