Sinon间谍/ Stub功能内部功能(私人功能)

时间:2016-12-21 10:01:16

标签: node.js mocha sinon

我是新人Sinon。我无法监视私人ajax功能

library.js

中的实际代码
function ajax () {
    console.log("I'm a");
}

function getJSON() {
    ajax();
    console.log("I'm b");
}

exports.getJSON = getJSON;

实际测试代码

var sinon = require('sinon');
var lib = require('./library');

describe('Tutor Test', function () {
    it('getJSON Calling ajax', function (done) {
        var ajax = sinon.spy(lib, 'ajax');
        lib.getJSON();

        ajax.restore();
        sinon.assert.calledOnce(ajax);
        done();
    });
});
  

注意:我已经尝试过以下对象示例。它就像魅力一样。

library.js

中的工作代码
var jquery = {
    ajax: function () {
        console.log("I'm a");
    },

    getJSON: function () {
        this.ajax();
        console.log("I'm b");
    }
};

exports.jquery = jquery;

工作测试案例。

var sinon = require('sinon');
var $ = require('./library').jquery;

describe('Tutor Test', function () {
    it('getJSON Calling ajax', function (done) {
        var ajax = sinon.spy($, 'ajax');
        $.getJSON();

        ajax.restore();
        sinon.assert.calledOnce(ajax);
        done();
    });
});

我在mocha test

期间收到如下错误
1) Tutor Test getJSON Calling ajax:
     TypeError: Attempted to wrap undefined property ajax as function
      at Object.wrapMethod (node_modules/sinon/lib/sinon/util/core.js:113:29)
      at Object.spy (node_modules/sinon/lib/sinon/spy.js:41:26)
      at Context.<anonymous> (test.js:41:26)

1 个答案:

答案 0 :(得分:4)

据我所知,在Sinon中无法使用间谍私人变量/功能。因此,请避免对这些用例使用Sinon

  

注意:您的(ajax)函数没有参数和返回值而且未绑定到导出的对象是sinon的真正挑战

在这种情况下,如果您想确定是否触发了ajax功能。您可以使用rewire

以下是工作代码。

var rewire = require('rewire');
var lib = rewire('./library');
const assert = require('assert');

describe('Tutor Test', function () {
    it('getJSON Calling ajax', function (done) {
        lib.__set__('isAjaxCalled', false);
        lib.__set__('ajax', function () {
            lib.__set__('isAjaxCalled', true);
        });

        lib.getJSON();
        assert.equal(lib.__get__('isAjaxCalled'), true);
        done();
    });
});
  

不更改您的实际代码,library.js