[英]How to test in JEST a request that downloads a file
我想在下面的代碼中對導出的方法進行單元測試。 嘗試為正在從localhost
服務器下載 zip 文件的 function 編寫單元測試。我將在下面編寫我的 function 以便您更好地理解:
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
的response
,我在測試中收到的是null
,沒有error
捕獲。 這是從 jest 收到的錯誤:
expect(received).toBeTruthy()
Expected value to be truthy, instead received false
當 mocking 請求時,您應該解決 promise。 我認為 promise 沒有解決這就是它不起作用的原因。 我希望下面的代碼將解決您的問題。
jest.mock('request', () => {
const mockRequest = {
pipe: jest.fn(),
on: (parameter, callback) => {
callback();
},
};
return function () {
return mockRequest;
};
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.