我有一个函数可以使用Node的fs异步地从文件系统读取文件内容。虽然这个函数可以工作,但我不能用Jest测试它。我正在使用mock-fs库模拟文件系统,以尝试测试该功能。
读取文件的函数: 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,因为正确地返回了文件数。错误处理例程工作并捕获未找到处理的文件,并通过。
但是,从mock读取实际文件的测试失败。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秒的超时时间内未返回,并显示以下错误:
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' );发布于 2021-06-30 23:33:40
在寻求更多帮助的过程中,我找到了解决方案。我目前使用的是Node15.9,从Node10(或者12 )开始,promises库可以更好地处理fs函数。
因此,我的ReadFileContents()代码变得非常简单,因为我可以简单地使用FS / readFile中的promise版本的fs promise。这样,错误将被抛出,或者文件将被异步读取,并且使用此函数的代码将处理数据或捕获抛出的错误。
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;
}https://stackoverflow.com/questions/68156442
复制相似问题