httpception

4.0.1 • Public • Published

httpception

NPM version Build Status Coverage Status Dependency Status

Mock out HTTP traffic during a test, experimentally extracted from unexpected-mitm:

var httpception = require('httpception');
var got = require('got');
var assert = require('assert');
 
it('should perform the right HTTP request', () => {
  httpception({
    request: 'GET http://example.com/foobar',
    response: {
      headers: {
        'Content-Type': 'text/plain',
      },
      body: 'the text',
    },
  });
 
  return got('example.com/foobar').then((response) => {
    assert.equal(response.body, 'the text');
  });
});

The http module will automatically be restored when the test ends. That is detected by registering an afterEach block and failing from that if you have unexercised mocks.

If you think that involves too much magic, you can also pass a function as the last parameter. It will be invoked by httpception when the mocks are in place, and the mocks will be removed after it has exited. If the function returns a promise, the mocks will be kept until the promise has resolved:

it('should perform the right HTTP request', () =>
  httpception(
    {
      request: 'GET /foobar',
      response: {
        statusCode: 200,
        body: 'the text',
      },
    },
    () => {
      return got('example.com/foobar').then((response) => {
        assert.equal(response.body, 'the text');
      });
    }
  ));

When the test is done, the http module will automatically be restored, and the test will fail if there are unexercised mocks.

Releases

Changelog

Readme

Keywords

none

Package Sidebar

Install

npm i httpception

Weekly Downloads

196

Version

4.0.1

License

BSD-3-Clause

Unpacked Size

47.5 kB

Total Files

15

Last publish

Collaborators

  • alexjeffburke
  • papandreou
  • gustavnikolaj