【发布时间】:2020-06-24 17:38:09
【问题描述】:
我正在尝试使用 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)
什么都不显示...?!有什么想法吗?
谢谢你,我要疯了……
【问题讨论】:
标签: node.js http testing mocha.js nock