shmock 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' ) ; 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.