javascript - 为什么我的 sinon fake 服务器不返回任何内容?

标签 javascript mocha.js sinon

我正在尝试设置一个假的 sinon 服务器来测试一些请求。在下面的代码中,我的回调函数永远不会被调用。测试错误 Error: timeout of 500ms超过。确保在此测试中调用done()回调。为什么回调函数没有立即被调用?

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

    });

最佳答案

您需要调用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

关于javascript - 为什么我的 sinon fake 服务器不返回任何内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36782755/

相关文章:

javascript - 在javascript中混合两种颜色 "naturally"

javascript - 如何改变 body 等级

node.js - Chai http - 双重回调问题

javascript - mocha + mongodb 等待异步结果

javascript - sinon stub.withArgs() 用于 stub 外部函数

node.js - 简单的 ProxyRequire 不起作用?

node.js - 与解构一起使用的 Sinon stub 函数

javascript - 如何在 d3js 中创建下一级流程图

javascript - 试图避免 javascript eval()

angularjs - 执行 gulp 任务时无法在 karma 配置文件上加载 "mocha"框架