【问题标题】:How to run function when any test fails - Jest任何测试失败时如何运行函数 - Jest
【发布时间】:2018-07-01 11:24:18
【问题描述】:

每当任何jest 测试失败时,我都想运行function / task。不是用 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'})

  })

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

【问题讨论】:

标签: javascript testing jestjs puppeteer


【解决方案1】:

为什么使用try/catch?

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

function runAssertion(assertion, onFailure) {
    try {
        assertion();
    } catch (exception) {
        onFailure();
        throw exception;
    }
}

然后这样称呼它:

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

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

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

【讨论】:

  • 这在使用toMatchSnapshot时似乎不起作用
  • @Jeremy 抱歉,我从未使用过toMatchSnapshot。失败时不能抛出异常。
  • 就是这样 - 请参阅 this github issue。我的SO answer here 提出了解决方案
  • 您不应该编写一个能够从测试运行器获取测试状态的方法......这充其量是一种解决方法,但仍然有点草率 imo
【解决方案2】:

@Tyler Clark 我没有用afterEach 尝试过这个,但我怀疑你可以应用类似my SO answer here 的东西。 (在下面粘贴它的一个版本以获取上下文 - 已更改为与 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
  });
});

【讨论】:

    【解决方案3】:

    在 Jasmine 中存储当前规范结果并在 afterEach 中访问它。

    1. specStarted 添加自定义 Jasmine 报告器并将规范结果存储到 jasmine.currentTest

      jasmine.getEnv().addReporter( {
        specStarted: result => jasmine.currentTest = result
      } );
      

      不直观的一点是,即使我们在结果出现之前将其存储在 specStarted 中,jasmine.currentTest 也会存储对 result 对象的引用,该对象将在规范运行时动态更新,所以当我们在afterEach 中访问它,它将正确保存规范的结果。

    2. 检查afterEach 中的failedExpectations,如果有任何故障,请截屏。

      afterEach( async () => {
        if ( jasmine.currentTest.failedExpectations.length > 0 ) { // There has been a failure.
          await driver.takeScreenshot(); // Or whatever else you want to do when a failure occurs.
        }
      } );
      

    【讨论】:

      猜你喜欢
      • 2020-05-05
      • 2018-11-21
      • 2020-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-31
      • 2013-05-24
      • 1970-01-01
      相关资源
      最近更新 更多