Utility for mocking XMLHttpRequests in the browser.
Useful for unit testing and doesn't require you to inject a mocked object into your code.
npm install --save xhr-mock
component install jameslnewell/xhr-mock
var mock = require('xhr-mock');
//replace the real XHR object with the mock XHR object
mock.setup();
//create a mock response for all GET requests with the URL http://localhost/api/user
mock.put('http://localhost/api/user', function(req, res) {
//return null; //simulate an error
//return res.timeout(true); //simulate a timeout
return res
.status(201)
.header('Content-Type', 'application/json')
.body(JSON.stringify({data: {
first_name: 'John', last_name: 'Smith'
}))
;
});
//create an instance of the (mock) XHR object and use as per normal
var xhr = new XMLHttpRequest();
...
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
//when you're finished put the real XHR object back
mock.teardown();
}
}
Examples of using xhr-mock
with various frameworks:
Replace the global XMLHttpRequest
object with the MockXMLHttpRequest
.
Restore the global XMLHttpRequest
object to its original state.
Register a factory function to create mock responses for each GET request to a specific URL.
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 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.
Get the request method.
Get the request URL.
Get a request header.
Get the request headers.
Get the request body.
Get the response status.
Set the response status.
Set a response header.
Get a response header.
Get the response headers.
Set the response headers.
Get the response body.
Set the response body.
Get whether the response will trigger a time out.
Set whether the response will trigger a time out. timeout
defaults to the value set on the XHR object.
- Ability to return mocked responses asynchronously
- Ability to provide a simple object response instead of a function
- Handle JSON and XML response types