mof-request
Version:
A middleware wrapped request.js module for floodesh
104 lines (85 loc) • 2.62 kB
JavaScript
const should = require('should')
const co = require('co')
const Mof = require('mof')
const request = require('../')
const sinon = require('sinon')
require('should-sinon')
describe('mof-request ', () => {
let log = function(a,b,c){console.log(a,b,c);};
let ctx, app,options, application={logger:{debug:log,info:log,verbose:log,warn:log,error:log}};
beforeEach(()=>{
app = new Mof();
ctx = {opt:{uri:'http://www.baidu.com'}, app:application, response:{},request:{},job:{uuid:"uuid"}};
options = {jar:true};
});
it('should exist', done => {
app.use(co.wrap(request(options)));
app.use((ctx, next) => {
should.exist(ctx.request.req);
should.exist(ctx.response.res);
return next();
});
const handle = app.callback( ctx => {
should.exist(ctx.request.req);
should.exist(ctx.response.res);
done();
});
handle(ctx);
});
it('should send tasks at once', done => {
let i=0;
const tasks = ["http://www.baidu.com","http://www.bing.com","http://www.163.com"].map(url=>{
return {opt:{uri:url, encoding:null}, app:application, response:{}, request:{}};
});
app.use(co.wrap(request()));
app.use((ctx, next) => {
ctx.response.res.body.length.should.above(0);
return next();
});
tasks.forEach(ctx=>app.callback(ctx => {
ctx.response.res.statusCode.should.eql(200);
if(++i===tasks.length)
done();
})(ctx));
});
it('should catch error while ETIMEDOUT.', done=>{
app.use(co.wrap(request({timeout:1})));
app.use((ctx, next) => {
console.log(ctx.url);
return next();
});
let context = {
opt:{
uri:"http://www.facebook.com/"
},
app:application,
response:{},
request:{}
};
let cb = sinon.spy();
app.callback(cb, e=>{
cb.should.not.be.called();
should.exist(e);
e.code.should.eql("ETIMEDOUT");
done();
})(context);
});
it('should use configuration correctly', done => {
let globalOptions = {headers:{"User-Agent":"bbc"}};
app.use((ctx, next) => {
ctx.opt.headers = ctx.opt.headers || {};
ctx.opt.headers["User-Agent"]="abc";
return next();
});
app.use(co.wrap(request(globalOptions)));
app.use((ctx, next) => {
ctx.opt.headers["User-Agent"].should.eql("abc");
return next();
});
app.callback(ctx => {
ctx.response.res.statusCode.should.eql(200);
done();
})(ctx);
});
});