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

时间:2018-01-22 18:39:13

标签: javascript testing jestjs puppeteer

每当function测试失败时,我想运行task / jest。不是用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检查......但是我想要对我的所有测试都更健壮。

3 个答案:

答案 0 :(得分:2)

为什么使用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的方法。

答案 1 :(得分: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
  });
});

答案 2 :(得分:0)

将当前规格结果存储在Jasmine中,并在<resources> <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> <item name="windowNoTitle">true</item> <item name="android:windowFullscreen">true</item> </style> </resources> 中进行访问。

  1. afterEach添加自定义的Jasmine报告程序,并将规范结果存储到specStarted

    jasmine.currentTest

    一个不直观的事情是,即使我们在结果存入之前将其存储在jasmine.getEnv().addReporter( { specStarted: result => jasmine.currentTest = result } ); 中,specStarted也会存储对jasmine.currentTest对象的引用,该引用会动态更新随着规范的运行,因此当我们在result中访问规范时,它将正确保存规范的结果。

  2. 在您的afterEach中检查failedExpectations,并在发生故障时进行截图。

    afterEach
相关问题