Jest 模拟请求.js超时 - 在 jest.setTimeout.Error: 指定的 5000 毫秒超时内未调用异



我正在尝试模拟请求.js来模拟文件上传,但它总是挂起。我增加了等待时间,但它总是会超时。

我试图模拟的代码遵循request.post.form.append结构。如果我手动输入表单数据,它总是失败,因此出于功能原因,无法修改功能代码。

我设置了我的 require.js mock 以仅适合一个用例,这就是为什么它是这样编写的。我的要求.js模拟如下:

const request = {
  post: jest.fn(() => ({
    form: jest.fn(() => ({
      append: jest.fn(test => {
        console.log(test)
        return Promise.resolve({
          status: 200,
          body: { test }
        })
      })
    }))
  }))
};
module.exports = request;

我的笑话代码如下:

    it('should upload a file', async () => {
      mocks.post.mockReturnValueOnce({
        status: 200,
        body: { test: 'response' }
      });
      const res = await dataSource.uploadFile(
        { name: 'projects', id: '123' },
        null,
        {
          filename: 'test',
          encoding: '7bit',
          mimetype: 'text/plain',
          createReadStream: jest.fn
        },
         '12345'
      );
      console.log('RES', res); // never gets here
      expect(mocks.post).toBeCalledWith('testName/123/files', {
        filename: 'test',
        encoding: '7bit',
        mimetype: 'text/plain',
        createReadStream: jest.fn
      });
      expect(res).toMatchSnapshot();
    });

适用的测试返回如下:

  console.log folder/folderName/src/files/__mocks__/request.js:5
    file
  console.log folder/folderName/src/files/__mocks__/request.js:5
    file
 FAIL  folder/folderName/src/files/__tests__/upload.spec.js (12.673s)
    uploadFile
      ✕ should upload a file (5006ms)
  ● FilesAPI › uploadFile › should upload a file
    Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Error: 

我注意到它在我的请求模拟中记录了两次test,所以我猜它正在等待其他东西正确返回。我错过了什么?

运行的代码非常适合实际上传,我只是在努力为它编写单元测试。

因此,您在此处指定的超时需要短于默认超时。

如果未调用此方法,则默认超时间隔为 5 秒。您可以通过添加

jest.setTimeout(10000); // 10 seconds

在官方文件解释中,

执行此操作的好地方是setupTestFrameworkScriptFile。 https://jestjs.io/docs/en/jest-object#jestsettimeouttimeout

在某些情况下,您只需要进行一次设置,并且如果您已经有jest.config.js文件。

// jest.config.js
module.exports = {
  // setup test framework after jest loaded
  setupFilesAfterEnv: [
    './tests/setupTestFrameworkScriptFile.js' // The path to a module that runs some code to configure or set up the testing framework before each test
  ],
};

现在我们可以为您拥有的每个测试用例进行 setTimout 一次性设置,

// ./tests/setupTestFrameworkScriptFile.js file
jest.setTimeout(10000) // we set timeout interval is 10 seconds for every test case
beforeAll(async () => {
  await initializeDatabase(); // this is just an example
  initializeOtherDepedency();
}, 3000) // assume we only need 3 seconds for initialization before runnng test case.

最后一个只是您的测试用例文件

// uploadfile.test.js
it('should upload a file', async () => {
})

另请参阅此文档:

https://jestjs.io/docs/en/configuration#setupfilesafterenv-array

https://jestjs.io/docs/en/jest-object#jestsettimeouttimeout

https://jestjs.io/docs/en/api#beforeallfn-timeout

相关内容

最新更新