shmock

shmock (GitHub: xetorthio/shmock, License: MIT) is a module by Jonathan Leibiusky provides a super nice API, like the one of superagent but it creates a real http server (using express). The nice thing about this is that you don’t really care about the implementation, which http client is being used, or even if nodes native http api changes.

 

1
npm install shmock

Usage

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var
  shmock = require('shmock'),
  request = require('request'),
  assert = require('assert')
  ;
var mock = shmock(9000);
mock
  .get('/foo')
  .query('a=1&b=2')
  .reply(200, 'Hello npmawesome.com')
  ;
request("http://localhost:9000/foo?b=2&a=1", function(err, response) {
  assert.equal(response.statusCode, 200);
  assert.equal(response.body, 'Hello npmawesome.com');
  mock.close();
  console.log('It worked!');
});

Checkout runnable example.

Closing Thoughts

Being able to mock APIs is a very powerful tool for BDD. You can prototype, design and test your consumer before implementing a line of code. Check out xetorthio/shmock github page for full documentation and test for examples of usage.

Post navigation

Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *