我想在下面的代码中对导出的方法进行单元测试。尝试为从 localhost
服务器下载 zip 文件的函数编写单元测试。我将在下面编写我的函数,以便您更好地理解:
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();
});
});
来自Promise
的响应
,我在测试中收到的null
,没有捕获error
。这是从 jest 收到的错误:
expect(received).toBeTruthy()
Expected value to be truthy, instead received false
最佳答案
在模拟请求时,您应该解决 promise 。我认为这个 promise 没有解决,这就是它不起作用的原因。我希望下面的代码能够解决您的问题。
jest.mock('request', () => {
const mockRequest = {
pipe: jest.fn(),
on: (parameter, callback) => {
callback();
},
};
return function () {
return mockRequest;
};
});
关于javascript - 如何在 JEST 中测试下载文件的请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58937598/