我尝试了很多次,但总是行不通。 我使用 Mocha 单元测试。 这是我的代码单元测试:
var expect = require("expect");
var jQuery = require("jquery");
var sinon = require("sinon");
describe("SinonFakeServerWithJasmine", function() {
var server;
beforeEach(function() {
server = sinon.fakeServer.create();
});
afterEach(function() {
server.restore();
});
it("should fake a jQuery ajax request", function() {
server.respondWith("GET", "/something", [200, {
"Content-Type": "application/json"
},
'{ "stuff": "is", "awesome": "in here" }'
]);
jQuery.ajax({
url: "/something",
success: function() {
console.log("success");
},
error: function(err) {
console.log(err);
}
});
server.respond(); // Process all requests so far
});
});
==> 这是日志错误 Jquery.ajax
{ readyState: 0,
getResponseHeader: [Function],
getAllResponseHeaders: [Function],
setRequestHeader: [Function],
overrideMimeType: [Function],
statusCode: [Function],
abort: [Function],
state: [Function],
always: [Function],
then: [Function],
promise: [Function],
pipe: [Function],
done: [Function],
fail: [Function],
progress: [Function],
complete: [Function],
success: [Function],
error: [Function],
status: 0,
statusText: 'TypeError: Invalid URL' }
我不知道为什么会这样。我没有使用 expect,因为在我的情况下没有必要,我想用 mocha 测试 sinon 感谢大家花时间阅读。
最佳答案
我在使用 Jasmine 时遇到了同样的无效 URL 问题。
我不得不使用 xmlhttprequest .
XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
jQuery.ajaxSettings.xhr = function() {
return new XMLHttpRequest();
};
关于javascript - Sinon.JS 错误 URL 无效,如何解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35138254/