首页 > 解决方案 > 如何在 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();
  });
});

responsePromise我收到里面的测试是null,没有error抓到。这是从 jest 收到的错误:

expect(received).toBeTruthy()

Expected value to be truthy, instead received false

标签: javascriptreactjsunit-testingjestjs

解决方案


在模拟请求时,您应该解决承诺。我认为这个承诺没有解决,这就是它不起作用的原因。我希望下面的代码将解决您的问题。

jest.mock('request', () => {
  const mockRequest = {
    pipe: jest.fn(),
    on: (parameter, callback) => {
       callback();
    },
  };
  return function () {
    return mockRequest;
  };
});


推荐阅读