Created
July 31, 2017 15:29
-
-
Save Maxim-Filimonov/a55099f8f4f0032da24d226bb8bc0e24 to your computer and use it in GitHub Desktop.
Sinon stubbing of function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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