# xhr-mocklet

> Utility for mocking XMLHttpRequests in the browser or nodejs.

Latest version **1.2.3** (published 2018-11-20) · MIT license · 0 weekly downloads

## Install

```sh
npm install xhr-mocklet
pnpm add xhr-mocklet
yarn add xhr-mocklet
bun add xhr-mocklet
```

## Health

**Score 30/100 (F)** — status: abandoned.

Positive: has types; esm support; no vulnerabilities; high quality score.

Warnings: low downloads.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.2.3 |
| Published | 2018-11-20 |
| First published | 2017-03-13 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Dependencies | 3 |
| Unpacked size | 134 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 5 |
| Maintainers | marvinhagemeister |
| Keywords | mock, xhr, test, fake, request, ajax, browser, xmlhttprequest |

## Links

- npm: https://www.npmjs.com/package/xhr-mocklet
- Repository: https://github.com/marvinhagemeister/xhr-mocklet
- Homepage: https://github.com/marvinhagemeister/xhr-mocklet#readme
- Issues: https://github.com/marvinhagemeister/xhr-mocklet/issues
- npm.io page: https://npm.io/package/xhr-mocklet

## Dependencies (3)

- [global](https://npm.io/package/global.md) ^4.3.1
- [event-emitter](https://npm.io/package/event-emitter.md) ^0.3.5
- [@types/event-emitter](https://npm.io/package/@types/event-emitter.md) ^0.3.0

## Alternatives

- [duck](https://npm.io/package/duck.md) — 4.2M weekly downloads
- [ava](https://npm.io/package/ava.md) — 560.2K weekly downloads
- [storybook-addon-module-mock](https://npm.io/package/storybook-addon-module-mock.md) — 71.7K weekly downloads
- [vest](https://npm.io/package/vest.md) — 50.1K weekly downloads
- [@ethereum-waffle/mock-contract](https://npm.io/package/@ethereum-waffle/mock-contract.md) — 40.0K weekly downloads

## Recent versions

- 1.2.3 (latest) — 2018-11-20
- 1.2.2 — 2018-03-23
- 1.2.1 — 2017-08-31
- 1.2.0 — 2017-08-29
- 1.1.0 — 2017-03-14
- 1.0.0 — 2017-03-13

## README

# XMLHttpRequest mocking

[![Build Status](https://travis-ci.org/marvinhagemeister/xhr-mocklet.svg?branch=master)](https://travis-ci.org/marvinhagemeister/xhr-mocklet) [![MIT](https://img.shields.io/npm/l/inferno.svg?style=flat-square)](https://github.com/marvinhagemeister/xhr-mocklet/blob/master/LICENSE.md)
[![NPM Version](https://img.shields.io/npm/v/xhr-mocklet.svg?style=flat-square)](https://www.npmjs.com/package/xhr-mocklet)

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

```bash
# NPM
npm install --save --dev xhr-mocklet

# Or via yarn:
yarn add --dev xhr-mocklet
```

## Usage

```js
const mock = require('xhr-mocklet');

// Replace the real XHR object with the mock XHR object
mock.setup();

// Mock a response for all POST requests to http://localhost/api/user
mock.post('http://localhost/api/user', (req, res) => {
  return res
    .status(201)
    .header('Content-Type', 'application/json')
    .body({
      lastName: 'John',
      firstName: 'Smith'
    });
});

// Restore the original XHR object when all your tests are done.
mock.teardown();
```

### Simulating an error

Simply return `null` from your response handler:

```js
mock.post('http://localhost/foo', (req, res) => null);
```

### Simulate a timeout

```js
mock.post('http://localhost/foo', (req, res) => res.timeout(true));
```

### Use mocked `XMLHttpRequest`

You can even use a mocked `XMLHttpReqeuest` instance to create Requests:

```js
// Create an instance of the (mock) XHR object and use as per normal
const xhr = new XMLHttpRequest();

xhr.onreadystatechange = () => {
  if (xhr.readyState === xhr.DONE) {
    // when you're finished put the real XHR object back
    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)` | Create `GET` mock response for a specific url. |
| `post(url: string \| regex, callback)` | Create `POST` mock response for a specific url. |
| `put(url: string \| regex, callback)` | Create `PUT` mock response for a specific url. |
| `patch(url: string \| regex, callback)` | Create `PATCH` mock response for a specific url. |
| `delete(url: string \| regex, callback)` | Create `DELETE` mock response for a specific url. |
| `mock(callback)` | Register mock response for every request. |

### MockXMLHttpRequest

The api is practically similar to the native [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/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` | Get weather the response will trigger a timeout. |
| `timeout(ms: boolean \| number)` | Set a timeout, otherwise default to the value set on the XHR object. |
| `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](https://github.com/jameslnewell/) for his
[xhr-mock](https://github.com/jameslnewell/xhr-mock) library. `xhr-mocklet`
started out as a fork of his work.

---
_Source: https://npm.io/package/xhr-mocklet · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
