简体   繁体   English

在node.js中使用sinon + mockery + chai进行单元测试

[英]unit testting using sinon+mockery+chai in node.js

I am very new to unit testing, so please guide me through the following: I am trying to unit test the following function... 我对单元测试非常陌生,因此请指导我完成以下工作:我正在尝试对以下功能进行单元测试...

helpers.js helpers.js

    function helpers() {
    }

    helpers.prototype.Amount = function(callback){
        var Amount = 0;
        app.models.xxx.find({}, function(err, res) {
            if(err){
            } else {
                for(var i=0; i < res.length; i++){
                    Amount = Amount + res[i].hhhh;
                }
                return callback(null,Amount);
            }
        });
    }
module.exports.helpers = helpers;

helpers-test.js helpers-test.js

describe('helper', function(){

var AmountStub = sinon.stub(Helper.protoype,"getAmount");
  it('should return the amount', function(done){
    var helper = new Helper();

    helper.getAmount(function(err, res){
      assert.ifError(err);
    });
    done();
  });
});

But i am receiving the following error: 但是我收到以下错误:

/node_modules/sinon/lib/sinon/util/core.js:67
                throw new TypeError("Should wrap property of object");
                      ^
TypeError: Should wrap property of object

Please guide me through this. 请指导我。 Also the way i am doing is right? 我做的方式也是对的吗? Thanks in advance.. 提前致谢..

EDIT: 编辑:

var Helper =  require("../../server/helpers").helpers;

    var helper = sinon.stub(
        new Helper(),
        "getAmount",
          function (callback) { callback(1000); }
          );
          helper.getAmount(
              function (value) { 
                expect(value).to.be.equal(1000);
                done();
              });
          });

According to the sinon docs you need to pass an object itself, not its prototype. 根据sinon文档,您需要传递一个对象本身,而不是其原型。

var helper = sinon.stub(new Helper(), "getAmount");

In your case you would like to do stubbing inside the it test and provide the replacement for the function: 在您的情况下,您想在it测试中进行存根it并提供该函数的替代品:

var helper = sinon.stub(
    new Helper(),
    "getAmount",
    function (callback) { callback(dummyValue); }
);
helper.getAmount(
    function (value) { done(); }
);

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

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