node.js - JestJS 测试不会因错误而失败

标签 node.js unit-testing typescript jestjs

我正在编写一个 typescript 库并使用 Jest 对其进行测试。这是我的代码:

export function populateTasks(inputFilePath: string): Task[] {
    if (!inputFilePath) {
        throw new Error("Input file path is null: " + inputFilePath);
    }
    const tasks: Task[] = [];
    readFile(inputFilePath, (err, data) => handleInputFile(err, data));
    return tasks;
}

function handleInputFile(err: any, data: any): void {
    if (err) {
        console.log("File not found");
        throw new Error("File not found: " + err);
    }
    console.log(data.toString());
}

这是我的测试:

describe("test", () => {
    test("just a test", () => {
        populateTasks("tasks"); // Invalid file path
    });
});

由于路径无效handleInputFile应该抛出一个错误并且测试应该失败。然而,目前它的打印文件未找到到控制台,但测试通过了。 如何让测试失败?

最佳答案

我认为应该是相反的:如果函数预计会抛出异常(给定无效路径),那么测试应该通过。

使用.toThrow(error) :

test("should throw if path is invalid", () => {
    expect(() => populateTasks("tasks")).toThrow();
});

test("should not throw if path is valid", () => {
    expect(() => populateTasks("../tasks")).not.toThrow();
});

关于node.js - JestJS 测试不会因错误而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48354511/

相关文章:

node.js - 在 AWS Cognito 中未收到带有 "adminCreateUser"函数的邮件

javascript - 使用 Jasmine 测试服务功能 POST 响应

javascript - componentDidMount 是否应该在 Enzyme 中以浅层渲染运行?

typescript - 如何修复 @typescript-eslint/no-misused-promises 错误

python - 使用 npm-install --save 时出现错误 : Can't find Python executable . ..(系统变量已设置 python)

node.js - NodeJS - MS Azure 物联网

mysql - node.js 使用两个表获取 mysql 数据

unit-testing - DART单元测试结果会追溯更改

typescript - 如何解决 TS7009 TypeScript 错误?

javascript - 嵌套 fb.group 和 fb.array 的补丁值 - react 形式