Sinon FakeServer没要求?
我正在遵循SinonJS Fake Server教程,并且正在运行以下简单代码:
var server;before(function () { server = sinon.fakeServer.create(); });
after(function () { server.restore(); });
it("calls callback with deserialized data", function () {
var callback = sinon.spy();
getTodos(42, callback);
// This is part of the FakeXMLHttpRequest API
server.requests[0].respond(
200,
{ "Content-Type": "application/json" },
JSON.stringify([{ id: 1, text: "Provide examples", done: true }])
);
assert(callback.calledOnce);
});
我将getTodos函数包含在同一文件中。这里也是:
function getTodos(listId, callback) { $.ajax({
url: "/todo/" + listId + "/items",
success: function (data) {
// Node-style CPS: callback(err, data)
callback(null, data);
}
});
}
但是,我遇到了错误TypeError: Cannot read property 'respond' of
undefined。看起来server.requests
是空的-这为什么呢?如何确保请求显示出来?
:我能够缩小问题的范围。我在getTodos函数中添加了一个“错误”回调,并在console.log中找到了该错误。事实证明,尝试执行jsdom节点模块时出现语法错误,urlObj
= new URL(uri,
documentBaseURLSerialized(this._ownerDocument));这随后导致$.ajax({
失败。有人对此有任何想法吗?
回答:
我能想到的一个问题是您没有在您的JSm实例中加载Sinon。这是在这里工作的测试文件:
var jsdom = require("jsdom");var assert = require("assert");
var vc = jsdom.createVirtualConsole();
vc.on("log", console.log.bind(console.log));
vc.on("jsdomError", function jsdomError(er) {
throw er;
});
var window;
var $;
var sinon;
before(function (done) {
jsdom.env({
html: "",
scripts: ["node_modules/jquery/dist/jquery.js",
"node_modules/sinon/pkg/sinon.js"],
features: {
ProcessExternalResources: ["script"],
FetchExternalResources: ["script", "link"],
},
virtualConsole: vc,
done: function _done(error, w) {
if (error) {
throw error;
}
window = w;
$ = w.$;
sinon = w.sinon;
done();
},
});
});
function getTodos(listId, callback) {
$.ajax({
url: "/todo/" + listId + "/items",
success: function (data) {
// Node-style CPS: callback(err, data)
callback(null, data);
}
});
}
var server;
before(function () { server = sinon.fakeServer.create(); });
after(function () { server.restore(); });
it("calls callback with deserialized data", function () {
var callback = sinon.spy();
getTodos(42, callback);
// This is part of the FakeXMLHttpRequest API
server.requests[0].respond(
200,
{ "Content-Type": "application/json" },
JSON.stringify([{ id: 1, text: "Provide examples", done: true }])
);
assert(callback.calledOnce);
});
以上是 Sinon FakeServer没要求? 的全部内容, 来源链接: utcz.com/qa/398870.html