我正在尝试设置一个假的 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/