Jestjs Jest测试的自定义失败消息
我正在测试一个部分随机输入的函数。无论发生什么情况,随机化的输入对象片段都应该工作,但是如果我碰巧遇到一个失败的案例,我想通过在失败消息中包含无效输入来了解它是什么 我如何让Jest显示一条故障消息,该消息的扩展范围不仅限于Jestjs Jest测试的自定义失败消息,jestjs,Jestjs,我正在测试一个部分随机输入的函数。无论发生什么情况,随机化的输入对象片段都应该工作,但是如果我碰巧遇到一个失败的案例,我想通过在失败消息中包含无效输入来了解它是什么 我如何让Jest显示一条故障消息,该消息的扩展范围不仅限于expect 以下是我的代码: describe("my module", () => { it("should pass with some randomized inputs", () => {
expect
以下是我的代码:
describe("my module", () => {
it("should pass with some randomized inputs", () => {
const partialRandomInput = {
name: "Hardcoded",
age: Math.random() * 100,
yearsOfExperience: Math.random() * 30
};
const actualOutput = myModule(partialRandomInput);
expect(actualOutput).toEqual(false); // If this fails I only see the expect comparison that happened, which may not be helpful
});
});
也许在我上面的代码中,唯一的失败是随机年龄小于5岁,随机经验年数小于10岁。当我的测试失败时,我想查看用于partialRandomInput
的值。不要使用随机输入进行测试。
即使代码要与随机数一起使用,也应该使用预定义的值对其进行测试,以确保结果一致。通过使用随机数,您无法确保使用的输入将覆盖实现中相同的“分支”
相反,您可以尝试使用一组预定义的值和预期结果
describe.each([
[10, 10, true],
[22, 10, false],
[35, 11, true],
[50, 3, false],
[60, 7, false],
])(
"with age: %p and yearsOfExperience: %p",
(age, yearsOfExperience, expected) => {
it(`should return: ${expected}`, () => {
expect(
myModule({
name: "Hardcoded",
age,
yearsOfExperience,
})
).toEqual(expected);
});
}
);
但是为了回答问题,您可以在执行测试之前生成随机数,然后您可以:
在测试描述中添加该值
很好,这非常有帮助,既可以解释我问题的直接答案,也可以指出更好的方法。
describe.each(
Array.from(new Array(10), () => [Math.random() * 100, Math.random() * 10])
)("with age: %p and yearsOfExperience: %p", (age, yearsOfExperience) => {
test(`returns false`, () => {
expect(
myModule({
name: "Hardcoded",
age,
yearsOfExperience,
})
).toBe(false);
});
});