node.js - 如何返回无效缓冲区以测试 API 调用?
问题描述
我目前正在学习如何在 Node.js 中编写单元测试。为此,我制作了一个可以进行 API 调用的小文件:
const https = require('https')
module.exports.doARequest = function (params, postData) {
return new Promise((resolve, reject) => {
const req = https.request(params, (res) => {
let body = []
res.on('data', (chunk) => {
body.push(chunk)
})
res.on('end', () => {
try {
body = JSON.parse(Buffer.concat(body).toString())
} catch (e) {
reject(e) //How can i test if the promise rejects here?
}
resolve(body)
})
})
req.end()
})
}
为了测试这个文件的快乐流程,我使用nock伪造了一个请求。但是我想测试是否JSON.parse
抛出错误。为此,我认为我必须伪造里面的数据Buffer.concat(body).toString()
。假数据应该是JSON.parse
无法解析的。这样我就可以测试承诺是否被拒绝。唯一的问题是,我该怎么做?
上面doARequest模块对应的测试文件:
const chai = require('chai');
const nock = require('nock');
const expect = chai.expect;
const doARequest = require('../doARequest.js');
describe('The setParams function ', function () {
beforeEach(() => {
nock('https://stackoverflow.com').get('/').reply(200, { message: true })
});
it('Goes trough the happy flow', async () => {
return doARequest.doARequest('https://stackoverflow.com/').then((res) => {
expect(res.message).to.be.equal(true)
});
});
it('Rejects when there is an error in JSON.parse', async () => {
//How can i test this part?
});
});
任何帮助/建议将不胜感激。
解决方案
现在你正在使用 nock 的简写来传回一个对象,即这一行:
nock('https://stackoverflow.com').get('/').reply(200, { message: true });
这与传回 JSON 字符串相同,或者:
nock('https://stackoverflow.com').get('/').reply(200, JSON.stringify({
message: true
}));
要强制JSON.parse
失败,只需传回一个无效的 JSON 字符串,例如:
nock('https://stackoverflow.com').get('/').reply(200, 'bad');
推荐阅读
- javascript - 如何从控制器传递列表以查看和显示
- php - (已解决)HTML + PHP + PHPMAILER
- qemu - 如何将 Packer 与磁盘映像而不是 ISO 文件一起使用?
- linux - 尝试自动执行从 Windows 到 Linux (BusyBox) 控制台的任务,该控制台需要用户交互才能终止
- c# - 如何更新使用元组的列表元素?
- ibm-cloud - IBM DB2 不显示结果
- r - 使用 R 中的变量选择列
- swift - 将 UInt32 转换为 4 字节 Swift
- javascript - Next.js 中的动态页面不会链接回普通页面
- selenium-webdriver - 硒。使用“EC.element_to_be_clickable”函数查找并单击按钮