在测试使用 Sinon 的 fakeXMLHttpRequest 的函数时,当我运行测试时,我得到:
Error: connect ECONNREFUSED 127.0.0.1:80
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1159:16)
我在我的 server.js 中提供了一个 Express 位置——它在使用时发送一个变量:
app.get('/config', function (req, res) {
res.send(avariable)
})
我在应用程序的函数中使用它,如下所示:
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", theUrl,false);// false for synchronous request
xmlHttp.send(null);
return xmlHttp.responseText;
}
它工作正常,可以满足我的需要。但是我需要为它写一个单元测试 - 到目前为止我有:
describe('config', function() {
var sinon = require('sinon');
const { httpGet } = require('../src/main/webapp/src/config')
beforeEach(function () {
this.xmlHttp = sinon.useFakeXMLHttpRequest();
this.requests = [];
this.xmlHttp.onCreate = function (xmlHttp) {
this.requests.push(xmlHttp);
}.bind(this);
});
afterEach(function () {
this.xmlHttp.restore();
});
it('how on earth do you get this to work', function (done) {
var data = {'foo': 'bar'};
var dataJson = JSON.stringify(data);
mid(function(err, result) {
result.should.deep.equal(data);
done();
});
this.request[0].respond(200, {'Content-Type': 'text/json'}, dataJson);
});
})
并运行
npm test
得到顶部描述的错误。