在 sinon 中模拟 HTTP 获取

Mock HTTP fetch in sinon

我正在尝试在 jsfiddle 中模拟 HTTP 提取。我不确定我做错了什么导致结果不等于模拟结果。

这是我的示例代码:(您可以在浏览器控制台中查看日志。)

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();

作为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.


此代码由 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' }
    });
}