Utility for mocking XMLHttpRequest
.
Great for testing. Great for prototyping while your backend is still being built.
Works in NodeJS and in the browser. Is compatible with Axios, jQuery, Superagent
and probably every other library built on XMLHttpRequest
. Standard compliant (http://xhr.spec.whatwg.org/).
If you are using a bundler like Webpack or Browserify then install xhr-mock
using yarn
or npm
:
yarn add --dev xhr-mock
Now import xhr-mock
and start using it in your scripts:
import mock from 'xhr-mock';
If you aren't using a bundler like Webpack or Browserify then add this script to your HTML:
<script src="https://unpkg.com/xhr-mock/dist/xhr-mock.js"></script>
Now you can start using the global, XHRMock
, in your scripts.
First off lets write some code that uses XMLHttpRequest
...
./createUser.js
// we could have just as easily use Axios, jQuery, Superagent
// or another package here instead of using the native XMLHttpRequest object
export default function(data) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState == XMLHttpRequest.DONE) {
if (xhr.status === 201) {
try {
resolve(JSON.parse(xhr.responseText).data);
} catch (error) {
reject(error);
}
} else if (xhr.status) {
try {
reject(JSON.parse(xhr.responseText).error);
} catch (error) {
reject(error);
}
} else {
reject(new Error('An error ocurred whilst sending the request.'));
}
}
};
xhr.open('post', '/api/user');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({data: data}));
});
}
Now lets test the code we've written...
./createUser.test.js
import mock from 'xhr-mock';
import createUser from './createUser';
describe('createUser()', () => {
// replace the real XHR object with the mock XHR object before each test
beforeEach(() => mock.setup());
// put the real XHR object back and clear the mocks after each test
afterEach(() => mock.teardown());
it('should send the data as JSON', async () => {
expect.assertions(2);
mock.post('/api/user', (req, res) => {
expect(req.header('Content-Type')).toEqual('application/json');
expect(req.body()).toEqual('{"data":{"name":"John"}}');
return res.status(201).body('{"data":{"id":"abc-123"}}');
});
await createUser({name: 'John'});
});
it('should resolve with some data when status=201', async () => {
expect.assertions(1);
mock.post('/api/user', {
status: 201,
reason: 'Created',
body: '{"data":{"id":"abc-123"}}'
});
const user = await createUser({name: 'John'});
expect(user).toEqual({id: 'abc-123'});
});
it('should reject with an error when status=400', async () => {
expect.assertions(1);
mock.post('/api/user', {
status: 400,
reason: 'Bad request',
body: '{"error":"A user named \\"John\\" already exists."}'
});
try {
const user = await createUser({name: 'John'});
} catch (error) {
expect(error).toMatch('A user named "John" already exists.');
}
});
});
Replace the global XMLHttpRequest
object with the MockXMLHttpRequest
.
Restore the global XMLHttpRequest
object to its original state.
Forget all the request handlers.
Register a factory function to create mock responses for each GET request to a specific URL.
mock.get(/\.*.json$/, {
body: JSON.stringify({ data: { id: "abc" } })
});
Register a factory function to create mock responses for each POST request to a specific URL.
Register a factory function to create mock responses for each PUT request to a specific URL.
Register a factory function to create mock responses for each PATCH request to a specific URL.
Register a factory function to create mock responses for each DELETE request to a specific URL.
Register a factory function to create mock responses for each request to a specific URL.
Register a factory function to create mock responses for every request.
Log errors thrown by handlers.
Get the request method.
Get the request URL.
Set a request header.
Get a request header.
Get the request headers.
Set the request headers.
Get the request body.
Set the request body.
Get the response status.
Set the response status.
Get the response reason.
Set the response reason.
Set a response header.
Get a response header.
Get the response headers.
Set the response headers.
Get the response body.
Set the response body.
Set the Content-Length
header and send a body. xhr-mock
will emit ProgressEvent
s.
import mock from 'xhr-mock';
mock.setup();
mock.post('/', {});
const xhr = new XMLHttpRequest();
xhr.upload.onprogress = event => console.log(event.loaded, event.total);
xhr.open('POST', '/');
xhr.setRequestHeader('Content-Length', '12');
xhr.send('Hello World!');
Set the Content-Length
header and send a body. xhr-mock
will emit ProgressEvent
s.
import mock from 'xhr-mock';
mock.setup();
mock.get('/', {
headers: {'Content-Length': '12'},
body: 'Hello World!'
});
const xhr = new XMLHttpRequest();
xhr.onprogress = event => console.log(event.loaded, event.total);
xhr.open('GET', '/');
xhr.send();
Return a Promise
that never resolves or rejects.
import mock from 'xhr-mock';
mock.setup();
mock.get('/', () => new Promise(() => {}));
const xhr = new XMLHttpRequest();
xhr.timeout = 100;
xhr.ontimeout = event => console.log('timeout');
xhr.open('GET', '/');
xhr.send();
A number of major libraries don't use the
timeout
event and usesetTimeout()
instead. Therefore, in order to mock timeouts in major libraries, we have to wait for the specified amount of time anyway.
Return a Promise
that rejects. If you want to test a particular error you an use one of the pre-defined error classes.
import mock from 'xhr-mock';
mock.setup();
mock.get('/', () => Promise.reject(new Error()));
const xhr = new XMLHttpRequest();
xhr.onerror = event => console.log('error');
xhr.open('GET', '/');
xhr.send();
If you want to mock some requests, but not all of them, you can proxy unhandled requests to a real server.
import mock, {proxy} from 'xhr-mock';
mock.setup();
// mock specific requests
mock.post('/', {status: 204});
// proxy unhandled requests to the real servers
mock.use(proxy);
// this request will receive a mocked response
const xhr1 = new XMLHttpRequest();
xhr1.open('POST', '/');
xhr1.send();
// this request will receieve the real response
const xhr2 = new XMLHttpRequest();
xhr2.open('GET', 'https://jsonplaceholder.typicode.com/users/1');
xhr2.send();
Requests can be delayed using our handy delay
utility.
import mock, {delay} from 'xhr-mock';
mock.setup();
// delay the request for three seconds
mock.post('/', delay({status: 201}, 3000));
Requests can be made on one off occasions using our handy once
utility.
import mock, {once} from 'xhr-mock';
mock.setup();
// the response will only be returned the first time a request is made
mock.post('/', once({status: 201}));
In case you need to return a different response each time a request is made, you may use the sequence
utility.
import mock, {sequence} from 'xhr-mock';
mock.setup();
mock.post('/', sequence([
{status: 200}, // the first request will receive a response with status 200
{status: 500} // the second request will receive a response with status 500
// if a third request is made, no response will be sent
]
));
MIT Licensed. Copyright (c) James Newell 2014.