Created
November 6, 2017 16:16
-
-
Save lkrych/ad537915c69f09ad597767655d2b9211 to your computer and use it in GitHub Desktop.
Stubbing the fetch API with sinon
This file contains hidden or 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
////Constants ////////////////////////////////////////////// | |
function jsonOk (body) { | |
var mockResponse = new window.Response(JSON.stringify(body), { //the fetch API returns a resolved window Response object | |
status: 200, | |
headers: { | |
'Content-type': 'application/json' | |
} | |
}); | |
return Promise.resolve(mockResponse); | |
} | |
const MOCK_JSON = { | |
'your keys' : 'your values' | |
}; | |
////Sinon ////////////////////////////////////////////////// | |
beforeEach(() => { | |
let stub = sinon.stub(window, 'fetch'); //add stub | |
stub.onCall(0).returns(jsonOk(MOCK_JSON)); | |
}); | |
afterEach(() => { | |
window.fetch.restore(); //remove stub | |
}); | |
//////////////////////////////////////////////////////////// |
I used this to stub fetch with Qunit too, like this:
QUnit.module('fetch_modules', {
beforeEach: function(assert) {
let stubbedFetch = sinon.stub(window, "fetch");
stubbedFetch.onCall(0).returns(jsonOk({}));
},
afterEach: function(assert) {
window.fetch.restore();
}
});
Hope that helps someone!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
great snippet! replace window with global and works like a charm in node!