我是新来的 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 forsinon
在这种情况下,如果您想确定 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/