【问题标题】:Why doesn't my sinon fake server return anything?为什么我的sinon假服务器不返回任何东西?
【发布时间】:2016-04-22 00:41:37
【问题描述】:

我正在尝试设置一个假的 sinon 服务器来测试一些请求。在下面的代码中,我的回调函数永远不会被调用。测试出错Error: timeout of 500ms exceeded. Ensure the done() callback is being called in this test. 为什么没有立即调用回调函数?

var request = require('request');
var sinon = require('sinon');

describe('Job gets data', function(){

    var server;

    beforeEach(function(){
        server = sinon.fakeServer.create();
    });

    afterEach(function(){
        server.restore();
    });

    context('When there is a GET request to /something', function(){

        it('will throw an error if response format is invalid', sinon.test(function(done){

            server.respondWith('GET', '/something', [200, { "Content-Type": "application/json" }, '{invalid: "data"}']);
            request.get('/something', function (err, response, body) {
                console.log(response);
                console.log(body);
                done();
            });
        }));

    });

【问题讨论】:

    标签: javascript mocha.js sinon


    【解决方案1】:

    您需要致电server.respond 以完成所有请求。 I found this Gist which gives an example.

    这是相关代码。

    server.respondWith("GET", "/something",
                       [200, { "Content-Type": "application/json" },
                        '{ "stuff": "is", "awesome": "in here" }']);
    
    var callbacks = [sinon.spy(), sinon.spy()];
    
    jQuery.ajax({
      url: "/something",
      success: callbacks[0]
    });
    
    jQuery.ajax({
      url: "/other",
      success: callbacks[1]
    });
    
    console.log(server.requests); // Logs all requests so far
    server.respond(); // Process all requests so far
    

    【讨论】:

      猜你喜欢
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 2020-07-24
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多