1

I am currently writing unit test case using jest for a method that used fs.readFile .I have been trying to test the logic inside the fs.readFile without no success.So i tried to log inside the function like below

My function to test

fileUpload = (request: Request, response: Response) => {
    // Reading the file
    fs.readFile(request.file.path, async (error, file) => {
        console.log('Hey i am inside')
        const entity = await this.model.fileUpload(x, y, z);
    });
};

My test case so far

    it('should perform file upload', async () => {
       ....
       await Promise.resolve(controller.fileUpload(request as Request, response as Response))
       ....
    });

Error Thrown


Cannot log after tests are done. Did you forget to wait for something async in your test? Attempted to log "Hey i am inside".


Why is this error shown,even when i return a resolved promise in the test file.I infer that the tests are completed before control enters fs.readFile. What should i do to wait for the completion of fs.readFile ?

Sathya Narayanan GVK
  • 849
  • 2
  • 16
  • 32

1 Answers1

0

fs.readFile doesn't return a Promise, and neither (from the snippet) does your code for the fileUpload to run an await against. You'd need to make fileUpload return a Promise which resolves when the entire function is done.

orta
  • 4,225
  • 1
  • 26
  • 34