我正在编写一个 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/