node.jsunit-testingjestjsmock-fs

Testing async fs.readfile with Jest and mock-fs has the tests timing out, even with 30 second time out


I have a function that reads the contents of a file from the file system asynchronously using Node's fs. While the function works, I cannot test it with Jest. I am using the mock-fs library to mock the file system to try to test the function.

The funtion that reads the file: read-file-contents.ts

import * as NodeJSFS from 'fs';
import * as NodeJSPath from 'path';

export async function ReadFileContents(Directory:string, FileName:string):Promise<string> {
    return new Promise<string>((resolve, reject) => {
        const PathAndFileName = NodeJSPath.format( { dir: Directory, base: FileName });

        NodeJSFS.readFile(
            PathAndFileName,
            (error: NodeJS.ErrnoException | null, FileContents: Buffer) => {
                if (error) {
                    reject(error);
                } else {
                    resolve(FileContents.toString());
                }
            },
        );
    });
}

The test file does have the mock-fs working, as the file count is returned properly, due to a directory and a file in the mock-fs. The error handling routine works and catches the file not found handling, and passes.

However, the test to read the actual file from the mock, fails. read-file-contents.spec.ts

import * as MockFS from 'mock-fs';
import { ReadFileContents } from './read-file-contents';

describe('ReadFileContents', () => {
    afterEach( () => {
        MockFS.restore();
    });
    beforeEach( () => {
        MockFS( {
            'datafiles': {
                'abc.txt': 'Server Name'
            }
        }, {
            // add this option otherwise node-glob returns an empty string!
            createCwd: false
        } );
    });

    it('should have the proper number of directories and files in the mocked data', () => {
        expect(MockFS.length).toBe(2);
    });

    it('should error out when file does not exist', async () => {
        try {
            await ReadFileContents('./', 'file-does-not.exist');
        } catch (Exception) {
            expect(Exception.code).toBe('ENOENT');
        }
    });

    it('should load the proper data from abc.txt', async () => {
        let FileContents:string;
        try {
            FileContents = await ReadFileContents('./datafiles', 'abc.txt');
            expect(FileContents).toBe('Server Name');
        } catch (Exception) {
            console.log(Exception);
            expect(true).toBeFalsy();   // Should not happen due to mock-fs file system
        }
    });
});

The last test does not return within the time out of 30 seconds with the following error:

 FAIL  src/library/file-handling/read-file-contents.spec.ts (57.175 s)
  ● ReadFileContents › should load the proper file data abc.hdr

    thrown: "Exceeded timeout of 30000 ms for a test.
    Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test."

  22 |      });
  23 |
> 24 |      it('should load the proper file data abc.hdr', async () => {
     |      ^
  25 |              let FileContents:string;
  26 |              try {
  27 |                      FileContents = await ReadFileContents('./datafiles', 'abc.hdr' );

Solution

  • In looking for more help, I found the solution. I am using Node 15.9 currently, and since Node 10 (or 12 anyhow), the promises library handles the fs functions much better.

    Therefore, my ReadFileContents() code has become much simpler, as I can simply use the promise version of FS readFile from fs/promises. This way the error will be thrown, or the file will be read asynchronously, and the code using this function, which already has a try/catch, will handle the data or catching the thrown error.

    import * as NodeJSFSPromises from 'fs/promises';
    import * as NodeJSPath from 'path';
    
    export async function ReadFileContents(Directory:string, FileName:string):Promise<string> {
        const PathAndFileName = NodeJSPath.format( { dir: Directory, base: FileName });
        const FileContents$:Promise<Buffer> = NodeJSFSPromises.readFile(PathAndFileName);
        const Contents:string = (await FileContents$).toString();
        return Contents;
    }