UNPKG

superagent-nock

Version:
174 lines (141 loc) 5.3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var mock = {}; // The base url var baseUrl; // Routes registry var routesMap = {}; // The current (last defined) route var currentRoute; var methodsMapping = { get: 'GET', post: 'POST', put: 'PUT', del: 'DELETE', patch: 'PATCH', head: 'HEAD' }; var isFunction = function isFunction(obj) { return !!(obj && obj.constructor && obj.call && obj.apply); }; var buildRoute = function buildRoute(method, url, reply) { return { method: method, url: "".concat(baseUrl).concat(url), reply: reply }; }; var buildRouteKey = function buildRouteKey(httpMethod, url) { return "".concat(httpMethod, " ").concat(url); }; var addRoute = function addRoute(method, url) { var route = buildRoute(method, url); var routeKey = buildRouteKey(route.method, route.url); routesMap[routeKey] = route; currentRoute = route; return mock; // for chaining }; // TODO: mock.delay; // Sugar methods to add routes by http methods Object.keys(methodsMapping).forEach(function (method) { var httpMethod = methodsMapping[method]; mock[method] = addRoute.bind(null, httpMethod); }); // Reply function mock.reply = function (status, result, headers) { if (!currentRoute) { throw new Error('Must call get, post, put, del or patch before reply'); } for (var _len = arguments.length, rest = new Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) { rest[_key - 3] = arguments[_key]; } currentRoute.reply = _objectSpread({ status: status, result: result, headers: headers }, rest); return mock; // chaining }; mock.clear = function () { routesMap = {}; return mock; // chaining }; var init = function init() { var requestBaseUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; baseUrl = requestBaseUrl; // Set the baseUrl return mock; }; var _default = function _default(superagent) { // don't patch if superagent was patched already if (superagent._patchedBySuperagentMocker) { // mock.clear() // sheldon: added reset here return init; } superagent._patchedBySuperagentMocker = true; // Patch the end method to shallow the request and return the result var reqProto = superagent.Request.prototype; var oldEnd = reqProto.end; reqProto.end = function end(cb) { // do not use function arrow to access to this.url and this.method var route = routesMap[buildRouteKey(this.method, this.url)]; var reply = route && route.reply; if (reply) { if (isFunction(reply.status)) { reply = reply.status(this.url) || { status: 500 }; } // sheldon: the correct superagent behavior is to have res even in error case var res = _objectSpread({ status: reply.status, body: reply.result, headers: reply.headers, ok: true }, reply); var err; if (reply.status >= 400) { err = _objectSpread({ status: reply.status, response: reply.result }, reply); res.ok = false; } try { cb && cb(err, res); } catch (e) { console.error('callback error', e.stack || e); var response = new superagent.Response({ res: { headers: {}, setEncoding: function setEncoding() {}, on: function on() {} }, req: { method: function method() {} }, xhr: { responseType: '', getAllResponseHeaders: function getAllResponseHeaders() { return 'a header'; }, getResponseHeader: function getResponseHeader() { return 'a header'; } } }); response.setStatusProperties(e.message); cb && cb(e, response); } /* TODO: delay: setTimeout(function() { try { cb && cb(null, current(state.request)); } catch (ex) { cb && cb(ex, null); } }, value(mock.responseDelay));*/ } else { oldEnd.call(this, cb); } }; return init; }; exports["default"] = _default;