我正在尝试使用nock拦截从我的应用程序到互联网的呼叫。
这里的目标是避免在测试时使用可变的外部API。
我要做的是:
describe('My awesome test', () => {
beforeEach(() => {
let scope = nock('http://www.myexternalapi.eu')
.log(console.log)
.post('/my/awesome/path')
.query(true)
.reply(200, response);
console.error('active mocks: %j', scope.activeMocks())
});
it('Should try to call my API but return always the same stuff ', () =>{
myService.doStuffWithAHttpRequest('value', (success) => {
// The answer must always be the same !
console.log(success);
});
})
// Other tests...
}
和myService.doStuffWithAHttpRequest('value',(success)是类似的东西:
const body = "mybodyvalues";
const options = {
hostname: 'myexternalapi.eu',
path: '/my/awesome/path',
method: 'POST',
headers: {
'Content-Type': 'application/xml'
}
};
const request = http.request(options, (response) => {
let body = "";
response.setEncoding('utf8');
response.on('data', data => {
body += data;
});
response.on('end', () => {
parser.parseString(body, (error, result) => {
// Do a lot of cool stuff
onSuccess(aVarFromAllTheCoolStuff);
});
});
});
[运行测试时,nock显示此:
active mocks: ["POST http://www.myexternalapi.eu:80/my/awesome/path/"]
似乎不错!但是我的请求不匹配,并且总是调用外部API!
我已经尝试过:
beforeEach(() => {
let scope = nock('http://www.myexternalapi.eu/my/awesome/path')
.log(console.log)
.post('/')
.query(true)
.reply(200, response);
console.error('active mocks: %j', scope.activeMocks())
});
也不起作用。
beforeEach(() => {
let scope = nock('myexternalapi.eu')
.log(console.log)
.post('/my/awesome/path')
.query(true)
.reply(200, response);
console.error('active mocks: %j', scope.activeMocks())
});
都不起作用,并显示一个奇怪的URL:
active mocks: ["POST null//null:443myexternalapi.eu:80/my/awesome/path/"]
加上有些奇怪:
Nock can log matches if you pass in a log function like this:
.log(console.log)
不显示任何内容...?!有什么主意吗?
谢谢你,我为此感到疯狂...
您提供给nock
和post
的值不太正确。试试这个。
let scope = nock('http://www.myexternalapi.eu')
.log(console.log)
.post('/my/awesome/path')
.reply(200, response);
传递给nock
的字符串参数必须是源,主机和协议,并且不能包含任何路径或搜索参数/查询信息。同样,post
方法应接收调用的路径。
尝试确定Nock与请求不匹配的原因时,一个有用的工具是debug
和debug
。因此,无论您运行的是什么测试,都请添加Nock has integrated。