首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Jest和mock-fs测试异步fs.readfile会导致测试超时,即使只有30秒的超时

使用Jest和mock-fs测试异步fs.readfile会导致测试超时,即使只有30秒的超时
EN

Stack Overflow用户
提问于 2021-06-28 09:01:29
回答 1查看 213关注 0票数 0

我有一个函数可以使用Node的fs异步地从文件系统读取文件内容。虽然这个函数可以工作,但我不能用Jest测试它。我正在使用mock-fs库模拟文件系统,以尝试测试该功能。

读取文件的函数: read-file-contents.ts

代码语言:javascript
复制
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,因为正确地返回了文件数。错误处理例程工作并捕获未找到处理的文件,并通过。

但是,从mock读取实际文件的测试失败。read-file-contents.spec.ts

代码语言:javascript
复制
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秒的超时时间内未返回,并显示以下错误:

代码语言:javascript
复制
 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' );
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-30 23:33:40

在寻求更多帮助的过程中,我找到了解决方案。我目前使用的是Node15.9,从Node10(或者12 )开始,promises库可以更好地处理fs函数。

因此,我的ReadFileContents()代码变得非常简单,因为我可以简单地使用FS / readFile中的promise版本的fs promise。这样,错误将被抛出,或者文件将被异步读取,并且使用此函数的代码将处理数据或捕获抛出的错误。

代码语言:javascript
复制
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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68156442

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档