Mock HTTP fetch in sinon

10,411

As fatso83 said in here:

Fetch is a different API from XHR. The underlying library of the XHR stubbing, nise, only supports XHR (and so does Sinon). You can check out sinonjs/nise#7 for some tips on how to accomplish this.


This code which is written by Mark Middleton also helped me to do the testing: (Sinon to mock a fetch call)

import sinonStubPromise from 'sinon-stub-promise';
import sinon from 'sinon'
sinonStubPromise(sinon)


let stubedFetch = sinon.stub(window, 'fetch') )

window.fetch.returns(Promise.resolve(mockApiResponse()));

function mockApiResponse(body = {}) {
    return new window.Response(JSON.stringify(body), {
       status: 200,
       headers: { 'Content-type': 'application/json' }
    });
}
Share:
10,411
Maryam Saeidi
Author by

Maryam Saeidi

Updated on June 05, 2022

Comments

  • Maryam Saeidi
    Maryam Saeidi almost 2 years

    I am trying to mock HTTP fetch in jsfiddle. I am not sure what I do wrong that makes the result not to be equal to the mock one.

    Here is my sample code: (You can see the logs in the browser console.)

    http://jsfiddle.net/maryam_saeidi/yredb06m/7/

    async function getUser(userId) {    
            var user = await fetch("http://website/api/users/" + userId);
        return user.json();
    } 
    
    mocha.setup("bdd");
    chai.should();
    var assert = chai.assert,
            expect = chai.expect;
    
    describe('getUser()', () => {
        let server;
    
        beforeEach(function() {
        server = sinon.fakeServer.create();
      });
    
      afterEach(function () {
        server.restore();
      });
    
      it('should return a user.', async () => {
        const response = await getUser(1);
        console.log("response:", response);
      });
    
      it('should return a user object', async () => {
        const userId = 10;
        server.respondWith("GET", "http://website/api/users/" + userId,[200, { "Content-Type": "application/json" },
                            '{ "id": "1", "username": "John", "avatar_url": "A_URL" }']);
        const response = getUser(userId);
        server.respond();
        response.then(function(result){
          console.log("result:",result); //The code doesn't get here
          result.should.deep.equal({ "id": "1", "username": "John", "avatar_url": "A_URL" });
          });
      });
    
    });
    
    mocha.run();