Brandon
Brandon

Reputation: 1617

Jest Mocked request.js Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Error:

I am trying to mock request.js to mock a file upload but it alway hangs. I have increased the waiting time but it will always timeout.

The code I am trying to mock follows the request.post.form.append structure. If I put the form data in manually it always fails so for functionality reasons, the functioning code cannot be modified.

I setup my require.js mock to suit only one use case which is why it is written the way it is. My require.js mock is as follows:

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;

My jest code is as follows:

    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();
    });

The applicable test return is as follows:

  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: 

I noticed that it logs test within my request mock twice, so I am guessing that it is waiting for something else to properly return. What am I missing?

The code it is running works great for actual uploads, I am just struggling to write a unit test for it.

Upvotes: 0

Views: 2818

Answers (1)

Eka putra
Eka putra

Reputation: 759

So the timeout you specify here needs to be shorter than the default timeout.

The default timeout interval is 5 seconds if this method is not called. You can specify the timeout inside the test by adding

jest.setTimeout(10000); // 10 seconds

On official documentation explained,

A good place to do this is in the setupTestFrameworkScriptFile. https://jestjs.io/docs/en/jest-object#jestsettimeouttimeout

In some cases, you only need to do setup once, and if You already have jest.config.js file.

// 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
  ],
};

Now we can do One-Time Setup for setTimout every test case you have,

// ./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.

And the last one is just your test case file

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

})

See also this doc:

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

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

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

Upvotes: 1

Related Questions