Sinon Spy / Stub for Function inside Function (Private Function)

Sinon Spy / Stub for Function inside Function (Private Function)

我是新来的 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();
    });
});

Note: I already tried with below object example. it works like charm.

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)

据我所知,在 Sinon 中不可能监视私有变量/函数。因此,请避免在这些用例中使用 Sinon

Note: Your (ajax) function does not have param and return value and not bind to the exported object is real challenge for 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();
    });
});

No Change your Actual code, library.js

从导出的 public API.

中调用您的方法
var jquery = {
    ajax: function () {
        console.log("I'm a");
    },

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

另一种方法是用提示调用console.log,然后监视日志。

ajax: function () {
  console.log("I'm a");
},
var ajax = sinon.spy(console, 'log');
$.getJSON();
sinon.assert.calledOnceWithExactly("I'm a")