XMLHttpRequest mocking
Utility for mocking XMLHttpRequests both in the browser and nodejs. It's primary
use case is for unit tests, allowing you to respond with mock responses, trigger
timeouts, etc.
This library comes with complete TypeScript declaration files.
Installation
npm install --save --dev xhr-mocklet
yarn add --dev xhr-mocklet
Usage
const mock = require('xhr-mocklet');
mock.setup();
mock.post('http://localhost/api/user', (req, res) => {
return res
.status(201)
.header('Content-Type', 'application/json')
.body({
lastName: 'John',
firstName: 'Smith'
});
});
mock.teardown();
Simulating an error
Simply return null
from your response handler:
mock.post('http://localhost/foo', (req, res) => null);
Simulate a timeout
mock.post('http://localhost/foo', (req, res) => res.timeout(true));
Use mocked XMLHttpRequest
You can even use a mocked XMLHttpReqeuest
instance to create Requests:
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState === xhr.DONE) {
mock.teardown();
}
}
API
Builder
Method | Description |
---|
setup() | Replace the global XMLHttpRequest object with the MockXMLHttpRequest . |
teardown() | Restore the global XMLHttpRequest object to its original state. |
reset() | Remove all request handlers. |
`get(url: string | regex, callback)` |
`post(url: string | regex, callback)` |
`put(url: string | regex, callback)` |
`patch(url: string | regex, callback)` |
`delete(url: string | regex, callback)` |
mock(callback) | Register mock response for every request. |
MockXMLHttpRequest
The api is practically similar to the native XMLHttpRequest.
MockRequest
Method | Description |
---|
method(): string | Get the request method. |
url(): string | Get the request URL. |
query(): object | Get the parsed query part of the request URL. |
header(name: string): string | Get a request header. |
headers(): object | Get all request headers. |
body(): string | Get the request body. |
MockResponse
Method | Description |
---|
status(): number | Get the response status. |
status(code: number) | Set the response status. |
header(name: string): string | Get a response header. |
header(name: string, value: string) | Set a response header. |
headers(): object | Get response headers. |
headers(headers: obejct) | Set response headers. |
body(): string | Get response body. |
body(body: string) | Set response body. |
`timeout(): boolean | number` |
`timeout(ms: boolean | number)` |
progress(loaded: number, total: number, lengthComputable: boolean) | Trigger progress event. Pass in loaded size, total size and if event is lengthComputable. |
Special Thanks
Special thanks goes to James Newell for his
xhr-mock library. xhr-mocklet
started out as a fork of his work.