Install
npm install ncck
`</pre>
### Use
Setup Mocking Obejct like this:
<pre>`var nock = require('nock')
var couchdb = nock('http://myapp.iriscouch.com')
.get('/user/1')
.reply(200,{
_id: '123ABC',
_rev: '945B8dDb1',
username: 'PG',
email: '[email protected]'
});
`</pre>
This setup says that we will intercept every HTTP call to `http://myapp.iriscouch.com`
It will intercept an HTTP GET request to `'users/1'` and reply with a status 200 and the body will contain a user representation in JSON
Then the test can call the module, and the module will do the HTTP requests.
#### Specifying hostname
The request hostname can be a string or a RegExp
<pre>`var scope = nock('http://www.example.com')
.get('/resource')
.reply(200, 'domain matched');
var scope = nock(/example\.com/)
.get('/resource')
.reply(200, 'domain regex matched');
`</pre>
#### Specifying path
The request path can be a string, a RegExp or a filter function and you can use any HTTP verb
<pre>`var scope = nock('http://www.example.com')
.get('/resource')
.replay(200, 'path matched');
var scope = nock('http://www.example.com')
.get(/resource$/)
.reply(200, 'path using regex matched');
var scope = nock('http://www.example.com')
.get(function(uri){
return uri.indexOf('cats') >= 0;
})
.reply(200, 'path using function matched');
`</pre>
#### Specifying Request Body
argument to the `get`, `post`, `put` or `delete` specifications like this:
<pre>`var scope = nock('http://www.example.com')
.post('/users', {
username: 'PG',
email: '[email protected]'
})
.reply(201, {
ok: true,
id: '123ABC',
rev: '946B7D1C'
});
`</pre>
The request body can be a string, a regexp, a jSON object or a function
<pre>`var scope = nock('http://www.example.com')
.post('/users', /[email protected]/gi)
.reply(201, {
ok: true,
id: '123ABC',
rev: '946B7D1C'
});
var scope = nock('http://www.example.com')
.post('/users', {
username: 'PG',
password: '/a.+'/,
email: '[email protected]'
})
.reply(201, {
ok: true,
id: '123ABC',
rev: '946B7D1C'
})
`</pre>
#### Specifying Replies
You can specify the return status code for a path on the first argument of reply like this:
<pre>`.reply(404)
`</pre>
Or specify the reply body as a string:
<pre>`.reply(200, 'Hello from google')
`</pre>
or as a JSON-encoded object:
<pre>`.reply(200, {
username: 'PG',
email: '[email protected]',
_id: 'awefrf'
})
`</pre>
or even as a file:
<pre>`.replyWithFile(200, __dirname+'/replies/user.json')
`</pre>
An asynchronous function that gets an error-first callback as last argument also works:
<pre>`.reply(201, function(uri, requestBody, cb){
fs.readFile('cat-poem.txt', cb); // Error-first callback
});