首页 > 解决方案 > 使用 Jest 测试真实文件系统返回空结果

问题描述

如果文件内容与预期结果匹配,我正在使用 Jest(在 Node.js 环境中与 TypeScript 结合使用)来测试真实文件系统(不是模拟)。

我的测试如下所示:

    test("getting a existing template", async () =>{
        await get_template(template_name).then((template)=>{
            console.log('template: ', template);
            expect(template).toBe(user_input_template);
        });
    });

函数 get_template() 是这样实现的:

export async function get_template(template_name: string) {
    let path = join(__dirname, `../templates/template-data/${template_name}.hbs`);

    return await read_template(path).then((data) => {
        console.log('common.ts: ',data);
        return data;
    });
}

和 read_template() 函数如下:

export async function read_template(path: string){
    return readFileSync(path).toString();
}

像这样手动调用get_template()函数时:

await get_template('template_name');`

接收到正确的输出字符串。但是当通过 Jest 测试环境调用该函数时,只返回一个空字符串。

我是否选择了错误的测试方法,我是否在测试这个异步函数时犯了一个明显的错误,或者这是否是 Jest 的问题?

标签: javascriptnode.jsunit-testingjestjsfilesystems

解决方案


推荐阅读