本文介绍了使用 Jest 和 mock-fs 测试 async fs.readfile 会使测试超时,即使超时 30 秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,它使用 Node 的 fs 从文件系统异步读取文件的内容.虽然该功能有效,但我无法使用 Jest 对其进行测试.我正在使用 mock-fs 库来模拟文件系统以尝试测试该功能.

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.

读取文件的函数:读取文件内容.ts

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

由于 mock-fs 中有一个目录和一个文件,测试文件确实让 mock-fs 工作,因为文件计数被正确返回.错误处理例程工作并捕获未找到处理的文件,然后通过.

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.

但是,从模拟中读取实际文件的测试失败了.读取文件内容.spec.ts

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

最后一次测试未在 30 秒内返回并出现以下错误:

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' );

推荐答案

在寻求更多帮助时,我找到了解决方案.我目前使用的是 Node 15.9,从 Node 10(或 12)开始,promises 库可以更好地处理 fs 函数.

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.

因此,我的 ReadFileContents() 代码变得更加简单,因为我可以简单地使用 fs/promises 中 FS readFile 的承诺版本.这样就会抛出错误,或者异步读取文件,使用这个函数的代码,已经有了try/catch,会处理数据或者捕获抛出的错误.

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

这篇关于使用 Jest 和 mock-fs 测试 async fs.readfile 会使测试超时,即使超时 30 秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 20:14