如何在任何测试失败时运行函数 - Jest

Tyl*_*ark 13 javascript testing jestjs puppeteer

我想在任何一次测试失败时运行一个函数/任务.而不是用try/catch包装我的所有测试或添加if检查,有没有办法可以利用afterEach?

如果测试失败,那么我希望它失败,只需运行一个单独的功能.

例如:

test('nav loads correctly', async () => {
    const listItems = await page.$$('[data-testid="navBarLi"]')

    expect(listItems.length).toBe(4)

    if (listItems.length !== 4)
      await page.screenshot({path: 'screenshot.png'})

  })
Run Code Online (Sandbox Code Playgroud)

这是添加一个if检查...但我希望我的所有测试更健壮.

Jer*_*emy 5

@Tyler Clark我还没有尝试过这样做,但我怀疑你可以应用与我的SO答案afterEach类似的东西。(在下面粘贴它的版本以供上下文 - 更改为与 一起使用)afterEach

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

describe('Describe test', () => {
  afterEach(() => {
    if (global[GLOBAL_STATE].state.snapshotState.matched !== 1) {
      console.log(`\x1b[31mWARNING!!! Catch snapshot failure here and print some message about it...`);
    }
  });

  it('should test something', () => {
    expect({}).toMatchSnapshot(); // replace {} with whatever you're trying to test
  });
});
Run Code Online (Sandbox Code Playgroud)


byx*_*xor 0

为什么使用 try/catch 呢?

如果您不喜欢它的外观,您可以将其丑陋隐藏在函数中:

function runAssertion(assertion, onFailure) {
    try {
        assertion();
    } catch (exception) {
        onFailure();
        throw exception;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后像这样调用它:

test('nav loads correctly', async () => {
    const listItems = await page.$$('[data-testid="navBarLi"]')

    runAssertion(
        () => { expect(listItems.length).toBe(4) },
        () => { await page.screenshot({path: 'screenshot.png'}) }
    )
})
Run Code Online (Sandbox Code Playgroud)

这是我们团队为避免到处使用 try/catch 而采取的方法。

  • 就是这样 - 请参阅[此 github 问题](https://github.com/facebook/jest/issues/5802)。我的[这里的答案](/sf/answers/4148121071/)解决了一个解决方案 (2认同)