node.js - 函数内部函数的 Sinon Spy/Stub(私有(private)函数)

标签 node.js mocha.js sinon

我是新来的 Sinon。我无法窥探私有(private) 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 测试 期间遇到如下错误

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 中不可能监视私有(private)变量/函数。因此,请避免在这些用例中使用 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

关于node.js - 函数内部函数的 Sinon Spy/Stub(私有(private)函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41260003/

相关文章:

javascript - 动态更改测试代码覆盖率的 require 语句的更好方法?

node.js - Mocha 未显示所有测试

javascript - 无法调用 res.send()

mocha.js - 使用SinonJS stub 和spy 同一个函数?

node.js - Elasticsearch 创建基于时间的索引

node.js - 在 Express.js 应用程序中存储来自 Google 日历 Node.js 示例的事件列表

node.js - Mocha 怎么知道只有我的异步测试才能等待和超时?

javascript - 如何使用 Sinon.js stub 动态对象方法?

javascript - 如果 Array.prototype.map() 没有返回,是否被正确使用

javascript - 为什么 react.js 不能识别自己的 node.js 模块?