Jest-Puppeteer 测试在没有输出的情况下随机失败

Jest-Puppeteer test randomly fails without output

我有以下测试用例:

it('User can logout', async () => {
    await helper.navClick('.header-user-action__logout');
    const url = page.url();
    console.log(url)
    await expect(url).toContain('auth');
});

helper.navClick 只是一个小包装:

async function navClick(selector, options) {
    return await Promise.all([page.waitForNavigation(), expect(page).toClick(selector, options)]);
}

大多数情况下,它会成功,但有时会被标记为失败:

    ✕ User can logout (569 ms)

  ● Login › User can logout





  console.log
    https://auth.example.com/auth/realms/example/protocol/openid-connect/auth?response_type=code&client_id=example-app&redirect_uri=https%3A%2F%2Fexample.com%2Fsso%2Flogin&state=807469fd-3ee5-4d93-8354-ca47a63e69a6&login=true&scope=openid

怎么会这样? url 多次包含“auth”,我没有看到任何其他可能导致测试失败的内容。

我通过设置自定义环境发现了问题:

const PuppeteerEnvironment = require("jest-environment-puppeteer");
const util = require('util');

class DebugEnv extends PuppeteerEnvironment {

    async handleTestEvent(event, state) {
        const ignoredEvents = ['setup', 'add_hook', 'start_describe_definition', 'add_test', 'finish_describe_definition', 'run_start',
            'run_describe_start', 'test_start', 'hook_start', 'hook_success', 'test_fn_start', 'test_fn_success', 'test_done',
            'run_describe_finish', 'run_finish', 'teardown'];
        if (!ignoredEvents.includes(event.name)) {
            console.log(new Date().toString() + " Unhandled event(" + event.name + "): " + util.inspect(event));
        }
    }
}

module.exports = DebugEnv;

在我的 package.json 中,我将 testEnvironment 设置为此 DebugEnv:

"jest": {
    "preset": "jest-puppeteer",
    "testEnvironment": "./debugenv.js",

通过这样做,我发现了一个与测试本身无关的错误(如果我没记错的话,与网络有关)。