Neverending Programming Mistakes
Miss any of our Open RFC calls?Watch the recordings here! »

httpception

3.0.0 • 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.

Keywords

none

Install

npm i httpception

DownloadsWeekly Downloads

141

Version

3.0.0

License

BSD-3-Clause

Unpacked Size

26.7 kB

Total Files

14

Last publish

Collaborators

  • avatar
  • avatar
  • avatar