i am quit new to sinon and rewire. I am trying to check if private function was called with in promise. Private function stubbed is getting called, But sinon not detecting the call. below is my code snipped.
var fileController = rewire('./file')
var stub = sinon.stub().returns("abc")
fileController.__set__('privFunc', stub)
fileController.sampleFunc()
expect(stub).to.be.called
let otherFile = require('otherFile')
var privFunc = function(data) {
}
var sampleFunc = function() {
otherFile.buildSomeThing.then(function(data) {
privFunc(data)
})
}
module.exports = {sampleFunc}
In above code snipped, privFunc is actually getting called ie. stub is getting called, But sinon not detecting call.
var privFunc = function(data) {
}
var sampleFunc = function() {
privFunc(data)
}
module.exports = {sampleFunc}
But this above snippet works fine. ie. when private function is called directly
Your otherFile.buildSomeThing
is async, you need to await it before checking if the privFunc
stub has been called.
eg:
file.js
let otherFile = require('otherFile')
var privFunc = function(data) {
}
var sampleFunc = function() {
return otherFile.buildSomeThing.then(function(data) {
privFunc(data)
})
}
module.exports = {sampleFunc}
file.test.js
var fileController = rewire('./file')
var stub = sinon.stub().returns("abc")
fileController.__set__('privFunc', stub)
fileController.sampleFunc().then(() => {
expect(stub).to.have.been.called;
});
If you're using mocha, you could use something like this:
describe('file.js test cases', () => {
let stub, reset;
let fileController = rewire('./file');
beforeEach(() => {
stub = sinon.stub().returns("abc");
reset = fileController.__set__('privFunc', stub);
});
afterEach(() => {
reset();
});
it('sampleFunc calls privFunc', async () => {
await fileController.sampleFunc();
expect(stub).to.have.been.called;
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.