requestmock
TypeScript icon, indicating that this package has built-in type declarations

1.4.3 • Public • Published

requestmock

npm version dependencies

Mock calls to request module. Compatible with request-promise.

Installation

$ npm install requestmock

Using with mockery

const requestMock = require('requestmock');
const mockery = require('mockery');

mockery.enable({ warnOnUnregistered: false });
mockery.registerMock('request', requestMock);

// make sure request is required after mockery is set up.
const request = require('request');

requestMock.register('get', 'http://google.com', function (opts, cb) {
	cb(null, { statusCode: 200 }, 'get mock');
});
request('http://google.com', function (err, response, body) {
	console.log(body == 'get mock');
});

Using with request-promise

Using requestMock with request-promise requires you to either rely on the global Promise library or specify a Promise library explicitly as shown below:

const requestMock = require('requestmock');
requestMock.configure({ Promise: require('some-promise-library') });

Documentation

  • requestmock(opts, cb)

The module exports a function that can be used in the same way as the request module.

By default, it forwards all calls to the request module. Otherwise, you can use the module's functions to register or deregister handlers based on url and method.

This is meant to be used in conjunction with mockery, to allow some http requests to be mocked and others to be executed normally, during testing.

  • .register(method, url, handler)

Setup a handler for a url. The handler will take two parameters, opts and callback, which are the same that were passed to the request module. The url can be either a string (representing an exact url) or a RegExp.

The handler should call the callback function passing an error object (null if success), a response-like object, and a string (http body).

The response-like object should define the properties as needed by your modules, typically at least the statusCode property.

  • .deregister([ method ], url)

Remove handler for given method and url. If method is omitted, all handlers are removed.

  • .log(enabled)

Enable or disable logging of all requests. Useful for inspecting all the outgoing requests of an application.

Support

If you're having any problem, please raise an issue on GitHub and the Resin.io team will be happy to help.

Tests

Run the test suite by doing:

$ npm install && npm test

Contribute

Before submitting a PR, please make sure that you include tests, and that coffeelint runs without any warning.

License

The project is licensed under the MIT license.

Readme

Keywords

none

Package Sidebar

Install

npm i requestmock

Weekly Downloads

7

Version

1.4.3

License

MIT

Unpacked Size

30.9 kB

Total Files

11

Last publish

Collaborators

  • balena.io