如何在 Puppeteer page.on 事件中使用 Mocha 断言? UnhandledPromiseRejectionWarning: 断言错误

How to use Mocha assertions inside Puppeteer page.on events? UnhandledPromiseRejectionWarning: AssertionError

我正在尝试 运行 Puppeteer 的 page.on('response') 事件中的断言,但是,抛出了以下错误并且测试错误地通过了:UnhandledPromiseRejectionWarning: AssertionError.

我读过返回一个 promise 应该可以解决问题,但是如果我不知道事件何时停止发出,我该如何解决这个 promise?

完整的示例代码如下:

const assert = require('assert');
const puppeteer = require('puppeteer');
const config = require('../config.json');

describe('Tests', function () {
    let browser;
    let page;

    this.timeout(30000);

    before(async function () {
        browser = await puppeteer.launch({
            headless: config.headless
        });
        page = await browser.newPage();
    });

    after(async function () {
        await browser.close();
    });

    it('No responses with blacklisted URLs', async function () {
        const blacklistedUrls = ['tia', 'example'];

        page.on('response', response => {
            blacklistedUrls.forEach(blacklistedUrl => {
                const contains = response.url().includes(blacklistedUrl);
                assert.equal(contains, false);
            });
        });

        await page.goto('http://google.com/');
    });
});

您可以在 page.on 的外部范围有一个数组来填充黑名单 URL,然后等待 page.goto 使用 page.goto waitUntil 完成页面加载] 选项并在页面加载结束时断言数组长度。您甚至可以使用该数组在断言消息中打印列入黑名单的 URL。

请阅读内联评论

it('No responses with blacklisted URLs', async function () {
    const blacklistedUrls = ['tia', 'example'];

    // Have an array to keep each blacklisted URLs
    const blacklistedUrlsFound = [];

    page.on('response', response => {
        // Use some instead forEach to evaluate the rule, it will be faster
        const hasBlacklistedUrls = blacklistedUrls.some(url => response.url().indexOf(url) >= 0);

        // If response url has blacklisted urls add the url to the array
        if (hasBlacklistedUrls) {
            blacklistedUrlsFound.push(response.url());
        }
    });

    // Visit tha page and wait for network to be idle (finish requesting external urls)
    await page.goto('http://google.com/', { waitUntil: ["networkidle0"] });

    // Finally assert using the blacklistedUrlsFound.length and print the black-listed urls
    assert.equal(blacklistedUrlsFound.length > 0, false,
        `There are black-listed URLs:\n${blacklistedUrlsFound.map(url => `\t${url}`).join('\n')}`);
});

您的测试将在没有任何异常错误的情况下运行,当然它会失败,因为响应 URL 至少包含 tia