Skip to content

Instantly share code, notes, and snippets.

@Maxim-Filimonov
Created July 31, 2017 15:29
Show Gist options
  • Save Maxim-Filimonov/a55099f8f4f0032da24d226bb8bc0e24 to your computer and use it in GitHub Desktop.
Save Maxim-Filimonov/a55099f8f4f0032da24d226bb8bc0e24 to your computer and use it in GitHub Desktop.
Sinon stubbing of function
function getTodos(listId, callback) {
helpers.makeHttpCall({
url: '/todo/' + listId + '/items',
success: function (data) {
// Node-style CPS: callback(err, data)
callback(null, data);
}
});
}
// This wrapper is required for our stubbing to work
const helpers = {
makeHttpCall: () => jQuery.ajax(arguments)
};
module.exports = { getTodos, helpers };
const sinon = require('sinon')
const { helpers, getTodos } = require("../index")
afterAll(function () {
// When the test either fails or passes, restore the original
// makeHttpCalll function (Sinon.JS also provides tools to help
// test frameworks automate clean-up like this)
helpers.makeHttpCall.restore();
});
it('makes a GET request for todo items', function () {
// That's the reason why we wrapped our function in an object... so that we can stub it.
sinon.stub(helpers, 'makeHttpCall');
//
getTodos(42, 'whatever');
// this will fail if you change the url that is passed into makeHttpCall function
expect(helpers.makeHttpCall.calledWithMatch({ url: '/todo/42/items' })).toBeTruthy();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment