1
0
mirror of https://github.com/verdaccio/verdaccio.git synced 2024-11-13 03:35:52 +01:00
verdaccio/test/functional/lib/request.js

116 lines
2.7 KiB
JavaScript
Raw Normal View History

2017-04-19 21:15:28 +02:00
const assert = require('assert');
const request = require('request');
2017-06-30 23:11:12 +02:00
const requestData = Symbol('smart_request_data');
const _ = require('lodash');
export class PromiseAssert extends Promise {
2017-06-30 23:11:12 +02:00
constructor(options) {
super(options);
}
status(expected) {
const selfData = this[requestData];
return injectResponse(this, this.then(function(body) {
try {
assert.equal(selfData.response.statusCode, expected);
} catch(err) {
selfData.error.message = err.message;
throw selfData.error;
}
return body;
}));
}
body_ok(expected) {
const self_data = this[requestData];
return injectResponse(this, this.then(function(body) {
try {
if (_.isRegExp(expected)) {
assert(body.ok.match(expected), '\'' + body.ok + '\' doesn\'t match ' + expected);
} else {
assert.equal(body.ok, expected);
}
assert.equal(body.error, null);
} catch(err) {
self_data.error.message = err.message;
throw self_data.error;
}
return body;
}));
}
body_error(expected) {
const self_data = this[requestData];
return injectResponse(this, this.then(function(body) {
try {
if (_.isRegExp(expected)) {
assert(body.error.match(expected), body.error + ' doesn\'t match ' + expected);
} else {
assert.equal(body.error, expected);
}
assert.equal(body.ok, null);
} catch(err) {
self_data.error.message = err.message;
throw self_data.error;
}
return body;
}));
}
request(callback) {
callback(this[requestData].request);
return this;
}
response(cb) {
const selfData = this[requestData];
return injectResponse(this, this.then(function(body) {
cb(selfData.response);
return body;
}));
}
send(data) {
this[requestData].request.end(data);
return this;
}
2017-04-19 21:15:28 +02:00
}
2017-06-30 23:11:12 +02:00
function injectResponse(smartObject, promise) {
promise[requestData] = smartObject[requestData];
2017-04-19 21:15:28 +02:00
return promise;
}
2017-06-30 23:11:12 +02:00
function smartRequest(options) {
const smartObject = {};
smartObject[requestData] = {};
smartObject[requestData].error = Error();
Error.captureStackTrace(smartObject[requestData].error, smartRequest);
2017-06-30 23:11:12 +02:00
const result = new PromiseAssert(function(resolve, reject) {
smartObject[requestData].request = request(options, function(err, res, body) {
if (err) {
return reject(err);
}
2017-06-30 23:11:12 +02:00
// store the response on symbol
smartObject[requestData].response = res;
resolve(body);
});
});
// console.log("--result->", result);
2017-06-30 23:11:12 +02:00
return injectResponse(smartObject, result);
}
export default smartRequest;