xhr-mock
xhr-mock copied to clipboard
Utilities are not bundled into standalone browser build
The once and delay utilities added in #65 are super-helpful. Unfortunately they are not included in the standalone browser build produced in dist/xhr-mock.js , as seen, for example, at https://unpkg.com/[email protected]/dist/xhr-mock.js as referenced in the docs section "Without a bundler".
Related issue: https://github.com/jameslnewell/xhr-mock/issues/54
I'm open to ideas! Potentially we could export a dist/xhr-mock-utils.js
bundle as its own UMD script containing proxy
, once
and delay
?
WDYT? Would you be interested in contributing this enhancement?
The same affects the proxy
. When xhr-mock
is used by including the browser script on a web page, its functionality is seriously limited.
Yes, either bundling the utilities in xhr-mock.js
and exposing as properties of XHRMock
, or adding xhr-mock-utils.js
with them will work well.
The file https://unpkg.com/browse/[email protected]/lib/proxy.browser.js
is not meant to be loaded on a web page directly, but it can be downloaded, edited and loaded from a local copy as a workaround. For example:
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ?
module.exports = factory(require('xhr-mock')) :
typeof define === 'function' && define.amd ?
define(['xhr-mock'], factory) :
(global.XHRMockProxy= factory(XHRMock));
}(this, (function (mock) { 'use strict';
function parseHeaders(string) {
var headers = {};
var lines = string.split('\r\n');
lines.forEach(function (line) {
var parts = line.split(':', 2), name = parts[0], value = parts[1];
if (name && value) {
headers[name] = value.replace(/^\s*/g, '').replace(/\s*$/g, '');
}
});
return headers;
}
function proxy(req, res) {
return new Promise(function (resolve, reject) {
var xhr = new mock.RealXMLHttpRequest();
// TODO: reject with the correct type of error
xhr.onerror = function (event) { return reject(event.error); };
xhr.onloadend = function () {
res
.status(xhr.status)
.reason(xhr.statusText)
.headers(parseHeaders(xhr.getAllResponseHeaders()))
.body(xhr.response);
resolve(res);
};
xhr.open(req.method(), req.url().toString());
var headers = req.headers();
Object.keys(headers).forEach(function (name) {
var value = headers[name];
xhr.setRequestHeader(name, value);
});
xhr.send(req.body());
});
}
return proxy;
})));
The same could be done with the utilities as a workaround. However, they have module dependencies, in comparison to the proxy
, which has none, and it will make this manual workaround tedious.
This issue will be resolved in v3
which is (very slowly) under development. The utilities and proxy
will be exposed as their own packages and UMD bundles.