pretenderjs / FakeXMLHttpRequest

A fake XMLHttpRequest object for testing in browsers
MIT License
65 stars 46 forks source link

onSend not documented #26

Open refractalize opened 8 years ago

refractalize commented 8 years ago

I want responses to be dependent on the request, so I was looking for a way to be called when a request was made, so that I could examine the request and make the appropriate response, like any normal server-side would.

I found onSend, on this line here: https://github.com/pretenderjs/FakeXMLHttpRequest/blob/master/src/fake-xml-http-request.js#L281

Which serves the purpose quite well, however I'm forced to use it like this:

var fakeXhr = require('fake-xml-http-request');

fakeXhr.prototype.onSend = function (xhr) {
  xhr.respond(200, {'Content-Type': 'text/plain'}, 'you requested ' + xhr.method + ' ' + xhr.url);
};

The bit I'm not sure about is, simply from an API point of view, that we should be overriding a method on the prototype. Shouldn't there be a more formal (and documented) API for responding to requests like this?

I'm thinking something like, perhaps: fakeXhr.on('request', function (xhr) { ... }), and fakeXhr.off('request', ...). Or fakeXhr.onrequest = function (xhr) { ... }.

Happy to make a PR if you have a preference.

By the way, I'm planning to use this in mock-xhr-router.