I am trying to stub getJSON, done and fail function of jquery using sinon.js and proxyquire but always I am getting an error that .getJSON, done and fail is not function.
const $ = require("jquery");
const Progress = (() => {
const getData = () => {
return $.getJSON();
};
const showProgressBars = () => {
getData()
.done(function (data) {
console.log(data);
})
.fail(function (e) {
console.log("error getting data.", e);
});
};
return {
getData,
showProgressBars
}
})();
module.exports=Progress;
Test
const proxyquire=require("proxyquire");
const sinon=require("sinon");
const expect=require("chai").expect;
describe("Progress", () => {
it("should call getJSON", (done) => {
const getJSONStub = sinon.stub();
const jquerySpy = sinon.stub().callsFake(() => {
return {
getJSON: getJSONStub,
};
});
const { getData } = proxyquire("../src/demo", {
jquery: jquerySpy,
});
getData();
expect(getJSONStub.callCount).to.be.eq(1);
done();
});
});
My requirement is to test these two functions but I am unable to do this. I already spent two days but unable to stub the getJSON, done and fail function.
Any help sould be highly appreciated
Use
sinon.stub()to stub$.getJSON()method and its returned valueJQuery.jqXHRwhich has.done()and.fail()callbacks. You can get the original callback passed in using.callsFake()method, after getting them, call these callbacks manually with mocked data or error.You don't need to use
proxyquirepackage.E.g.
index.js:index.test.js:unit test result: