gpt4 book ai didi

javascript - 使用 Nock 模拟 NodeJS 请求和响应

转载 作者:行者123 更新时间:2023-12-03 05:32:14 28 4
gpt4 key购买 nike

我正在尝试掌握该工具Nock为了模拟我的代码执行调用的请求和响应。我使用 npm request 作为简单的 HTTP 客户端来请求后端 REST API,使用 Chai 作为期望库,使用 Mocha 来运行我的测试。这是我用于测试的代码:

 var nock = require('nock');
var storyController = require('../modules/storyController');

var getIssueResponse = {
//JSON object that we expect from the API response.
}

it('It should get the issue JSON response', function(done) {
nock('https://username.atlassian.net')
.get('/rest/api/latest/issue/AL-6')
.reply(200, getIssueResponse);

storyController.getStoryStatus("AL-6", function(error, issueResponse) {
var jsonResponse = JSON.parse(issueResponse);

expect(jsonResponse).to.be.a('object');
done();
})
});

这是执行 GET 请求的代码:

 function getStoryStatus(storyTicketNumber, callback) {
https.get('https://username.atlassian.net/rest/api/latest/issue/' + storyTicketNumber, function (res) {

res.on('data', function(data) {
callback(null, data.toString());
});

res.on('error', function(error) {
callback(error);
});
})
}

这个测试通过了,我不明白为什么。看起来它实际上是在进行真正的调用,而不是使用我的假诺克请求/响应。如果我评论箭尾部分或更改:

 .reply(200, getIssueResponse) to .reply(404)

它不会破坏测试,也不会发生任何变化,我没有对 nock 变量做任何事情。有人可以用一个清晰​​的示例向我解释如何使用 Nock 在 NodeJS http 客户端中模拟请求和响应吗?

最佳答案

TLDR:我认为您的代码所做的事情超出了它告诉您的范围。

重要提示:将 http 请求放入 "stream mode"data 事件可能(并且可能确实)被触发多次,每次触发一个数据“ block ”,通过互联网 block 可能在 1400 到 64000 字节之间变化,因此预计多次 回调调用(这是一种非常特殊的错误)

作为一个简单的建议,您可以尝试使用 request或者只是连接接收到的数据,然后调用 end 事件的回调。

我使用后一种技术尝试了一个非常小的片段

var assert = require('assert');
var https = require('https');
var nock = require('nock');

function externalService(callback) {
// directly from node documentation:
// https://nodejs.org/api/https.html#https_https_get_options_callback
https.get('https://encrypted.google.com/', (res) => {

var data = '';
res.on('data', (d) => {
data += d;
});

res.on('end', () => callback(null, JSON.parse(data), res));
// on request departure error (network is down?)
// just invoke callback with first argument the error
}).on('error', callback);
}


describe('Learning nock', () => {
it('should intercept an https call', (done) => {
var bogusMessage = 'this is not google, RLY!';

var intercept = nock('https://encrypted.google.com').get('/')
.reply(200, { message: bogusMessage });

externalService((err, googleMessage, entireRes) => {
if (err) return done(err);

assert.ok(intercept.isDone());
assert.ok(googleMessage);
assert.strictEqual(googleMessage.message, bogusMessage);
assert.strictEqual(entireRes.statusCode, 200);

done();
});

})
})

即使使用on('data'),它也能正常工作

编辑:

Reference on how to handle correctly a stream

我已将示例扩展为成熟的摩卡示例

关于javascript - 使用 Nock 模拟 NodeJS 请求和响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40894178/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com