gpt4 book ai didi

jestjs - Jest toMatchSnapshot 不会引发异常

转载 作者:行者123 更新时间:2023-12-02 03:38:58 25 4
gpt4 key购买 nike

大部分Jest如果比较与预期不符,则expect(arg1).xxxx()方法将抛出异常。此模式的一个异常(exception)似乎是 toMatchSnapshot() 方法。它似乎永远不会抛出异常,而是存储失败信息以供以后的 Jest 代码处理。

我们怎样才能使 toMatchSnapshot() 抛出异常?如果这不可能,我们的测试是否可以通过其他方法检测快照比较失败的情况?

最佳答案

这会起作用的!运行 toMatchSnapshot 断言后,检查全局状态:expect(global[GLOBAL_STATE].state.snapshotState.matched).toEqual(1);

刚刚花了最后一个小时试图弄清楚我们自己的测试。这对我来说也不觉得很麻烦,尽管 Jest 的维护者可能会告诉我访问 Symbol.for('$$jest-matchers-object') 是否是一个好主意。这是上下文的完整代码片段:

const GLOBAL_STATE = Symbol.for('$$jest-matchers-object');

describe('Describe test', () => {
it('should test something', () => {
try {
expect({}).toMatchSnapshot(); // replace with whatever you're trying to test
expect(global[GLOBAL_STATE].state.snapshotState.matched).toEqual(1);
} catch (e) {
console.log(`\x1b[31mWARNING!!! Catch snapshot failure here and print some message about it...`);
throw e;
}
});
});

关于jestjs - Jest toMatchSnapshot 不会引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49285231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com