Javascript 正确使用sinon';s伪XMLHttpRequest
我正在创建XMLHttpRequestJavaScript模块以从服务器获取JSON数据。代码如下:Javascript 正确使用sinon';s伪XMLHttpRequest,javascript,node.js,xmlhttprequest,mocha.js,sinon,Javascript,Node.js,Xmlhttprequest,Mocha.js,Sinon,我正在创建XMLHttpRequestJavaScript模块以从服务器获取JSON数据。代码如下: (function() { var makeRequest = function(url,callback,opt) { var xhr; if (XMLHttpRequest) { // Mozilla, Safari, ... xhr = new XMLHttpRequest(); } else if (ActiveXObject) { // IE
(function() {
var makeRequest = function(url,callback,opt) {
var xhr;
if (XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
} else if (ActiveXObject) { // IE
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!xhr) {
callback.call(this,
'Giving up :( Cannot create an XMLHTTP instance',
null);
return false;
}
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var data = xhr.responseText;
if(opt && !opt.raw) {
try {
data = JSON.parse(data);
} catch (e) {
callback.call(this, e,null);
return;
}
}
callback.call(this,null,data);
} else {
callback.call(this,
'There was a problem with the request.',
null);
}
}
};
var params = '';
if (opt && opt.params && typeof(opt.params) == 'object') {
for( var key in opt.params) {
params += encodeURIComponent(opt.params[key]);
}
}
var method = opt && opt.method ? opt.method : 'GET';
if (method == 'GET') {
url = params.length > 0 ? url+'?'+params : url;
xhr.open('GET', url);
xhr.send();
} else if (method == 'POST') {
var data = opt && opt.data ? opt.data : params;
xhr.open('POST', url);
xhr.send(JSON.stringify(data));
}
return xhr;
}
if(typeof module !== 'undefined' && module.exports) {
module.exports = makeRequest;
}
if(typeof window!== 'undefined') {
window.getJSONData = makeRequest;
}
})();
现在我正在与Mocha和Sinon一起在nodejs上为此编写测试用例。使用Sinon的fakeXMLHttpRequest测试模块和测试代码如下:
var expect = require('chai').expect,
getJSON = require('../'),
sinon = require('sinon');
describe('get-json-data test the request', function() {
beforeEach(function() {
this.xhr = sinon.useFakeXMLHttpRequest();
var requests = this.requests = [];
this.xhr.onCreate = function (xhr) {
requests.push(xhr);
};
});
afterEach(function() {
this.xhr.restore();
});
it('get json data', function() {
var callback = sinon.spy();
getJSON('/some/json', callback);
expect(this.requests.length).to.equal(1);
this.requests[0].respond(200,
{"Content-Type": "application/json"},
'{"id": 1, "name": "foo"}');
sinon.assert.calledWith(callback, {"id": 1, "name": "foo"});
});
});
运行测试时,我收到错误:
ReferenceError:未定义XMLHttpRequest
这似乎是正确的,因为nodejs中没有XMLHttpRequest类/函数。但Sinon的fakeXMLHttpRequest不应该这样做吗。我认为在Sinon的设置(Mocha之前的设置)中,我们正在用fakeXMLHttpRequest替换原生XMLHttpRequest。
请说明我做错了什么?或者,在nodejs上测试我的模块的正确方法是什么?因为您是在浏览器环境之外运行的,所以没有
XMLHttpRequest
对象。因为您正在用Sinon模拟它,所以您可以在每次调用之前在中声明一个伪全局函数
global.XMLHttpRequest = sinon.useFakeXMLHttpRequest();
我这样做是为了覆盖XMLHttpRequest(请参阅我的问题和答案):
感谢@timhc22的更新,现在我正在使用Sinon,所以Sinon的useFakeXMLHttpRequest对我来说很好。是的,我正在node.js环境中测试。但有了你的暗示,它就行了。谢谢@yashua。如果您使用的是FakeServer而不是FakeXMLHttpRequest,请将server.xhr中的对象放入global.XMLHttpRequest。
var FakeXMLHTTPRequests = require('fakexmlhttprequest')
var requests = []
XMLHttpRequest = function() {
var r = new FakeXMLHTTPRequests(arguments)
requests.push(r)
return r
}