Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

xhr-mock

jameslnewell608.7kMIT2.5.1TypeScript support: included

Utility for mocking XMLHttpRequest.

mock, xhr, test, fake, request, ajax, browser, xmlhttprequest, jquery, superagent, axios

readme

xhr-mock

npm (tag) Build Status npm

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/).

Documentation

Installation

Using a bundler

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';

Without a bundler

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.

Usage

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.');
    }
  });
});

API

xhr-mock

.setup()

Replace the global XMLHttpRequest object with the MockXMLHttpRequest.

.teardown()

Restore the global XMLHttpRequest object to its original state.

.reset()

Forget all the request handlers.

.get(url | regex, mock)

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" } })
});

.post(url | regex, mock)

Register a factory function to create mock responses for each POST request to a specific URL.

.put(url | regex, mock)

Register a factory function to create mock responses for each PUT request to a specific URL.

.patch(url | regex, mock)

Register a factory function to create mock responses for each PATCH request to a specific URL.

.delete(url | regex, mock)

Register a factory function to create mock responses for each DELETE request to a specific URL.

.use(method, url | regex, mock)

Register a factory function to create mock responses for each request to a specific URL.

.use(fn)

Register a factory function to create mock responses for every request.

.error(fn)

Log errors thrown by handlers.

MockXMLHttpRequest

MockRequest

.method() : string

Get the request method.

.url() : MockURL

Get the request URL.

.header(name : string, value: string)

Set a request header.

.header(name : string) : string | null

Get a request header.

.headers() : object

Get the request headers.

.headers(headers : object)

Set the request headers.

.body() : string

Get the request body.

.body(body : string)

Set the request body.

MockResponse

.status() : number

Get the response status.

.status(code : number)

Set the response status.

.reason() : string

Get the response reason.

.reason(phrase : string)

Set the response reason.

.header(name : string, value: string)

Set a response header.

.header(name : string) : string | null

Get a response header.

.headers() : object

Get the response headers.

.headers(headers : object)

Set the response headers.

.body() : string

Get the response body.

.body(body : string)

Set the response body.

How to?

Simulate progress

Upload progress

Set the Content-Length header and send a body. xhr-mock will emit ProgressEvents.

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!');

Download progress

Set the Content-Length header and send a body. xhr-mock will emit ProgressEvents.

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();

Simulate a timeout

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 use setTimeout() instead. Therefore, in order to mock timeouts in major libraries, we have to wait for the specified amount of time anyway.

Simulate an error

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();

Proxying requests

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();

Delaying requests

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));

Once off requests

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}));

send a sequence of responses

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
  ]
));

License

MIT Licensed. Copyright (c) James Newell 2014.

changelog

Change log

2.5.1

2.5.0

  • added the sequence() utility function (#83)

2.4.1

  • fix: check for DOM specific classes before checking for an instance of them so that environments without them e.g. mocha without jsdom mostly works

2.4.0

  • added once and delay utility functions.
  • changed the signature of MockURL.query from {} to {[name: string]: string}

2.3.2

  • fix: proxy all response bodies, not just text (#62)

2.3.1

  • fix: format the default error message better (#57)
  • fix: IE11 which chokes on URLSearchParams (#58)

2.3.0

  • added support for requests with Blob, FormData or URLSearchParams bodies
  • log errors thrown/rejected in handlers by default but allow logging to be customised

2.2.0

  • added "support" for responseType of arraybuffer, blob and document by returning whatever object res.body(body) is set to

2.1.0

  • added support for responseType="json"

2.0.4

  • fix: improve compliance of .response

2.0.3

  • improving the documentation

2.0.2

  • fix: version badge on README.md

2.0.1

  • fix: undefined __generator in UMD bundle due to #85

2.0.0

  • released with updated docs

2.0.0-preivew.15

  • fix (potential break): when async=false loadstart and progress events are no longer emitted according to the spec
  • fix (potential break): on error, timeout and abort the correct sequence of events are fired (#41)
  • fix (potential break): changed the error and onabort to be ProgressEvents like the latest spec (and different to the typescript types)

2.0.0-preivew.14

  • fix: made the proxy work in NodeJS

2.0.0-preivew.13

  • fix: examples in README.md

2.0.0-preivew.12

  • added a non-minified UMD bundle - ./dist/xhr-mock.js

2.0.0-preivew.11

  • added proxy - a handler for proxying requests as real XHR
  • added XHRMock.RealXMLHttpRequest
  • deprecated XHRMock.mock() in favor of XHRMock.use()
  • removed debugger statements and added linting
  • fix: made MockXMLHttpRequest implement XMLHttpRequest and missing enum values on the instance e.g. DONE

2.0.0-preview.10

  • fixed a bug where the body would not be sent when it was an empty string (#32)

2.0.0-preview.9

  • added support for RegExp in typings (#36)

2.0.0-preview.8

  • added typings to package.json

2.0.0-preview.6

  • break: removed MockRequest.progress() and MockResponse.progress()

2.0.0-preview.5

  • added an export for the real XMLHttpRequest object
  • fix: made MockObject props optional
  • break: changed the signature of the URL returned from MockRequest.url()

2.0.0-preview.4

  • fix: fixed a bug with upload progress

2.0.0-preview.3

  • fix: include transpiled files in published package

2.0.0-preview.2

  • added types
  • added support for mock objects
  • break: changed the ordering of MockRequest.progress() and MockRequest.progress()

2.0.0-preview.1

  • added support for upload progress
  • break: renamed MockResponse.statusText() to MockResponse.reason()
  • break: removed MockRequest.query() and changed MockRequest.url() to return a URL object (with a .toString() method)
  • break: removed MockResponse.timeout() - instead, return a promise that never resolves
  • break: moved MockRequest.progress() to MockResponse.progress() and added MockRequest.progress()
  • break: removed support for component

1.9.1

1.9.0

  • added Response.statusText() for setting the status text

1.8.0

  • added support for regexes instead of URLs in all the mock methods
  • added the .query() method to the request object
  • added the .reset() method to mock and MockXMLHttpRequest
  • added withCredentials to the mocked XHR objects (used by some libraries to test for "real" XHR support)

1.7.0

  • added support for addEventListener (#15)