在sinon中模拟HTTP提取

时间:2017-08-29 18:46:28

标签: javascript unit-testing mocha jsfiddle 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();

1 个答案:

答案 0 :(得分:5)

正如fatso83 here所说的那样:

  

Fetch是与XHR不同的API。 XHR存根的底层库nise只支持XHR(Sinon也是如此)。您可以查看sinonjs/nise#7以获取有关如何完成此操作的一些提示。


这段由Mark Middleton编写的代码也帮助我进行了测试:(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' }
    });
}