javascript - 如何在 JEST 中测试下载文件的请求
问题描述
我想在下面的代码中对导出的方法进行单元测试。尝试为从服务器下载 zip 文件的函数编写单元测试。localhost
我将在下面编写函数,以便您更好地理解:
export const downloadCdn = async (cdnUrl, out) => {
const download = (resolve, reject) => {
const req = request({
method: 'GET',
uri: cdnUrl
});
req.on('response', (data) => {
// do something
});
req.on('error', (data) => {
// do something
});
req.on('data', (chunk) => {
// do something
});
req.on('end', () => {
console.log('download done');
});
req.pipe(out);
out.on('close', () => {
resolve([null, 'done']);
});
};
const downloadSummary = new Promise(download);
return downloadSummary
.then(() => [null, 'Done'])
.catch(err => [err, null]);
};
这是我的测试文件,我想要实现的是进行单元测试来验证 zip 文件的下载:
import request from 'request';
import * as Module from './downloadCdn';
jest.mock('request', () => {
const mockRequest = {
pipe: jest.fn(),
on: jest.fn(),
};
return function () {
return mockRequest;
};
});
describe('Downloading a file', () => {
it('Should find the module', () => {
expect(typeof Module.downloadCdn === 'function').toBeTruthy();
});
it('Should download the zip', async () => {
const [error, response] = await Module.downloadCdn(cdnUrl, out);
expect(response === 'Done').toBeTruthy();
expect(error === null).toBeTruthy();
});
});
从response
,Promise
我收到里面的测试是null
,没有error
抓到。这是从 jest 收到的错误:
expect(received).toBeTruthy()
Expected value to be truthy, instead received false
解决方案
在模拟请求时,您应该解决承诺。我认为这个承诺没有解决,这就是它不起作用的原因。我希望下面的代码将解决您的问题。
jest.mock('request', () => {
const mockRequest = {
pipe: jest.fn(),
on: (parameter, callback) => {
callback();
},
};
return function () {
return mockRequest;
};
});
推荐阅读
- c# - 在数据库中存储照片的字节数
- python - Discum:“GatewayServer”对象没有属性“subscribeToGuildEvents”
- networking - 2个路由器之间的IP地址?
- python - GTK 不在网格内移动项目
- html - 有没有办法在使用标签中操作 href 的子项的属性?
- javascript - 交叉口观察者和动画数字计数器
- image-processing - 为什么 Microsoft 将其 HSL 范围重新调整为 [0-240]?
- sql-server - 适用于 Windows 的 sybase odbc 驱动程序
- .net-core - 使用 --no-build 发布 ReadyToRun 依赖于框架的 lambda
- plaid - Stripe 返回“没有这样的令牌”错误(格子集成)