npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

heisennock

v0.4.1

Published

TDD-friendly HTTP mocking for nodeJS

Downloads

13

Readme

heisennock

Build Status codecov Greenkeeper badge

heisennock is a TDD-friendly wrapper for the awesome HTTP mocking library nock. It totally removes the assertion logic from nock, focusing on the mocking and making contract checking a breeze by using the assertion library of your choice (chai...).

"I am the one who nocks." Walter White, a.k.a. Heisenberg

I am the one who knocks

Contract checking?

Asserting on mocks (HTTP or other stubs) call parameters is the key to do proper contract checking. Too often, developers tend to squeeze this part because it does not bring any "coverage". However, mocking without asserting on parameters is nothing but a coverage lie, leaving the code vulnerable to possible regressions whch could easily be avoided.

Why a wrapper?

While nock is perfect for mocking outbound HTTP calls, it unfortunately also tries to handle the assertion part. The resulting mix between matching rules and assertions can end up making TDD very unpratical:

  • we do not know for sure the callback was called and how many times
  • no helpful stacktrace (because the assertion is done in a callback)
  • no helpful diff

See the following snippet for a concrete example.

const nock = require('nock');

// recommended by nock's documentation
const myNock = nock('http://localhost:9876')
  .post('/some/path', { message: 'Say my name!' })
  .reply(201);

theCallWeAreTesting();

// test a call with the body: { message: 'Wrong message :(' }
// => ends up with a `Nock: No match for request ...` Error, no helpful stacktrace

For a more TDD-friendly way of failing, we could come up with the following hack:

const nock = require('nock');

// hijacking nock's API
let body;
const myNock = nock('http://localhost:9876')
  .post('/some/path', _body => {
    body = _body;  // use a closure to "capture" the body
    return true;  // lie to the nock matcher so we can handle our assertion later
  })
  .reply(201);

theCallWeAreTesting();

// => now we'll get a proper diff and stacktrace, and know exactly why we failed
expect(body).to.deep.equal({ message: 'Say my name!' });

"Oh my god, this is ugly!"

This is far more maintainable and makes for more robust tests. But, this is indeed ugly and discourages developers to do proper contract checking.

This is where Heisennock comes in:

const { hnock } = require('heisennock');

// Now we get to keep both:
// 1) the lean API of the original nock
const myNock = hnock('http://localhost:9876')
  .post('/some/path')
  .reply(201);

theCallWeAreTesting();

// 2) a simple way of doing a proper maintainable assertion
expect(myNock.body()).to.deep.equal({ message: 'Say my name!' });

Install

$ npm install heisennock

Use

Always clean after your tests

For maintainable tests, we recommend you to always call cleanAll after each test. This way you always leave a non-polluted HTTP layer behind you.

With mocha, this will is typically done as follows:

const { hnock } = require('heisennock');

describe('...', () => {
  afterEach(() => hnock.cleanAll());

  // the tests
})

Always perform assertions

As said above, it is critical to perform proper contract checking on your mocks. Always assert that the following items are matching your expectations:

  • numbers of calls
  • headers
  • bodies
  • querystrings
const myNock = hnock('http://localhost:9876')
  .post(/^\/api//)
  .reply(201);

theCallWeAreTesting();

// simple APIs for single calls (covers most cases)
expect(myNock.callCount).to.equal(1);
expect(myNock.url()).to.equal('/api/path');
expect(myNock.header('authorization')).to.equal('Bearer token');
expect(myNock.headers('authorization', 'accept'))
  .to.deep.equal({ authorization: 'Bearer token', accept: 'application/json' });
expect(myNock.body()).to.deep.equal({ message: 'Say my name!' });
expect(myNock.query()).to.deep.equal({ q: 'heisenberg' });

Support for multiple calls

// array APIs for multiple calls
expect(myNock.callCount).to.equal(2);
expect(myNock.urls()).to.deep.equal([
  '/api/path',
  '/api/other_path'
]);
expect(myNock.allHeaders('authorization')).to.deep.equal([
  { authorization: 'Bearer token1' },
  { authorization: 'Bearer token2' }
  );
expect(myNock.bodies()).to.deep.equal([
  { message: 'Say my name!' },
  { message: 'You\'re goddam right!' }
]);
expect(myNock.queries()).to.deep.equal([
  { q: 'walter' },
  { q: 'white' }
]);

Supported nock features

replyWithError()

Same as the original method from nock.

const myNock = hnock('http://localhost:9876')
  .post('/some/path')
  .replyWithError({ code: 'ECONNREFUSED' });

replyWithFile()

Same as the original method from nock.

const myNock = hnock('http://localhost:9876')
  .post('/some/path')
  .replyWithFile(200, path.join(__dirname, 'fixture.json'), { 'Content-Type': 'application/json' });

times()

Same as the original method from nock. times can be useful to test different behaviours on a same route, typically for a retry logic.

const myFirstNock = hnock('http://localhost:9876')
  .post('/some/path')
  .times(1)
  .replyWithError({ code: 'ECONNREFUSED' });

const mySecondNock = hnock('http://localhost:9876')
  .post('/some/path')
  .times(1)
  .reply(200, 'success');

By default, heisennock uses Infinity because we want multiple calls to be detected by assertion, not matching.

  • If you want to make sure your nock was called once, make an assertion on callCount
  • If you want to simulate several behaviours on a same route, use times