首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >来自Mock FS的Jest测试节点JS文件错误

来自Mock FS的Jest测试节点JS文件错误
EN

Stack Overflow用户
提问于 2021-06-22 00:42:13
回答 2查看 120关注 0票数 0

我遵循了基本的示例,并且使用异步文件读取,我不能测试文件读取的失败。使用Mock-FS进行测试,成功的案例都通过了,但是失败生成了一个未处理的异常错误。

ReadFileContents.ts

代码语言:javascript
复制
import * as NodeJSFS from 'fs';

export async function ReadFileContents(Directory:string, FileName:string):Promise<string> {
    return new Promise<string>((resolve, reject) => {
        NodeJSFS.readFile(
            `${Directory}/${FileName}`,
            (error: NodeJS.ErrnoException | null, FileContents: Buffer) => {
                if (error) {
                    reject(error);
                } else {
                    resolve(FileContents.toString());
                }
            },
        );
    });
}

ReadFileContents.spec.ts

代码语言:javascript
复制
import * as MockFS from 'mock-fs';
import { ReadFileContents } from './read-file-contents';

describe('ReadFileContents', () => {
    afterAll( async () => {
        MockFS.restore();
    });
    afterEach( async () => {
        MockFS.restore();
    });
    beforeEach( async () => {
        MockFS( {
            'datafiles': {
                'abc.txt': '{ "FirstLine": "This is the first line", "LastLine": "This is the last line" }',
                'abc.hdr': 'Server|MyServer',
            }
        }, {
            // add this option otherwise node-glob returns an empty string!
            createCwd: false
        } );
    });

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

    it('should load the proper file data abc.txt', async () => {
        ReadFileContents('./datafiles', 'abc.txt').then( FileContent => {
            expect(FileContent).toContain('This is the first line');
        });
    });

    it('should load the proper file data from abc.hdr', async () => {
        ReadFileContents('./datafiles', 'abc.hdr').then( FileContent => {
            expect(FileContent).toContain('Server');
        });
    });

    // it('should return an exception when the file does not exist', async () => {
    //  expect(async () => await ReadFileContents('./datafiles', 'FileDoesNotExist.Missing')).not.toThrow();
    // });
});

此外,此测试将具有相同的错误:

代码语言:javascript
复制
it('should return an exception when the file does not exist', async () => {
    await expect(ReadFileContents('./datafiles', 'FileDoesNotExist.Missing'))
        .rejects
        .toThrow();
});

对于丢失的文件,上述错误处理将生成以下错误:

代码语言:javascript
复制
node:internal/process/promises:245
          triggerUncaughtException(err, true /* fromPromise */);
          ^

[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "Error: EBADF, bad file descriptor".] {
  code: 'ERR_UNHANDLED_REJECTION'

如果没有错误条件测试,即使测试通过了,我也会得到以下单元测试的警告错误。

代码语言:javascript
复制
node:internal/process/promises:245
          triggerUncaughtException(err, true /* fromPromise */);
          ^

[Error: EAGAIN: resource temporarily unavailable, read] {
  errno: -11,
  code: 'EAGAIN',
  syscall: 'read'
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-06-30 23:37:06

我用https://stackoverflow.com/a/68197740/755666的答案解决了这个问题。我更改了代码以使用fs/promises版本的readFile。

我将代码更改为:

代码语言: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用户

发布于 2021-06-22 03:16:26

在catch块中,您正在拒绝错误。错误类型应为字符串,因为您期望promise返回字符串。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68071720

复制
相关文章

相似问题

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