Skip to content

Instantly share code, notes, and snippets.

@lkrych
Created November 6, 2017 16:16
Show Gist options
  • Save lkrych/ad537915c69f09ad597767655d2b9211 to your computer and use it in GitHub Desktop.
Save lkrych/ad537915c69f09ad597767655d2b9211 to your computer and use it in GitHub Desktop.
Stubbing the fetch API with sinon
////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
});
////////////////////////////////////////////////////////////
@sombriks
Copy link

great snippet! replace window with global and works like a charm in node!

@dreynolds
Copy link

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