Nodejs中,使用nock做http请求的mock

时间:2021-08-22 23:17:51

nock 可以拦截nodejs向外发送的HTTP请求,并模拟HTTP服务器响应,返回特定的结果,这对于接口测试非常方便。

// 例子更改自: 
// https://github.com/node-nock/nock#use
// 和
// https://github.com/node-nock/nock#repeat-response-n-times

var nock = require('nock');
var http = require('http');

var couchdb = nock('http://myapp.iriscouch.com')// 拦截所有发送到这个host(支持字符串和正则表达式)的http请求
.get('/users/1')// 对发送到这个path(支持字符串和正则表达式)的http请求作出响应; 对其他path的http请求报错
.times(2)
.reply(200, {
_id: '123ABC',
_rev: '946B7D1C',
username: 'pgte',
email: 'pedro.teixeira@gmail.com'
});

function _o(msg){console.log(msg);}

function doGet(path){
http.get({hostname: 'myapp.iriscouch.com', path: path}, (res)=>{
res.setEncoding('utf8');
if(res.statusCode == 200){
var newData = '';
res.on('data', (chunk)=>{ newData += chunk; });
res.on('end', () =>{
_o(newData);
});
} else{
_o('res.statusCode = ' + res.statusCode);
}
}).
on('error', (err)=>{
_o('error: ' + err);
});
}

doGet('/users/1'); // {"_id":"123ABC","_rev":"946B7D1C","username":"pgte","email":"pedro.teixeira@gmail.com"}
doGet('/users/10'); // error: Error: Nock: No match for request GET http://myapp.iriscouch.com/users/10
doGet('/users/1?x=b'); // error: Error: Nock: No match for request GET http://myapp.iriscouch.com/users/1?x=b
doGet('/users/1'); // {"_id":"123ABC","_rev":"946B7D1C","username":"pgte","email":"pedro.teixeira@gmail.com"}
doGet('/users/1'); // error: Error: Nock: No match for request GET http://myapp.iriscouch.com/users/1