Jest toMatchSnapshot 不抛出异常

use*_*334 2 jestjs

如果比较不符合预期,大多数Jest的 expect(arg1).xxxx() 方法将抛出异常。这种模式的一个例外似乎是 toMatchSnapshot() 方法。它似乎从不抛出异常,而是存储失败信息以供后续 Jest 代码处理。

我们如何导致 toMatchSnapshot() 抛出异常?如果这是不可能的,我们的测试是否可以通过另一种方式检测快照比较失败的时间?

Jer*_*emy 5

这会奏效!运行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;
    }
  });
});
Run Code Online (Sandbox Code Playgroud)