Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

xhr-mocklet

Package Overview
Dependencies
Maintainers
1
Versions
6
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

xhr-mocklet

Utility for mocking XMLHttpRequests in the browser or nodejs.

  • 1.2.2
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
71K
decreased by-4.4%
Maintainers
1
Weekly downloads
 
Created
Source

XMLHttpRequest mocking

Build Status MIT NPM Version

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
npm install --save --dev xhr-mocklet

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

Usage

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:

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:

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

MethodDescription
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.

MockRequest

MethodDescription
method(): stringGet the request method.
url(): stringGet the request URL.
query(): objectGet the parsed query part of the request URL.
header(name: string): stringGet a request header.
headers(): objectGet all request headers.
body(): stringGet the request body.

MockResponse

MethodDescription
status(): numberGet the response status.
status(code: number)Set the response status.
header(name: string): stringGet a response header.
header(name: string, value: string)Set a response header.
headers(): objectGet response headers.
headers(headers: obejct)Set response headers.
body(): stringGet response body.
body(body: string)Set response body.
timeout(): boolean | numberGet 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 for his xhr-mock library. xhr-mocklet started out as a fork of his work.

Keywords

FAQs

Package last updated on 23 Mar 2018

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc