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

问题描述 投票:0回答:1

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

我已经读到,返回承诺应该可以解决问题,但是如果我不知道事件何时将停止发出,如何解决承诺?

这里是完整的示例代码:

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/');
    });
});
javascript node.js mocha puppeteer
1个回答
0
投票

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

请阅读内嵌注释

waitUntil

您将在没有任何异常错误的情况下使您的测试正常进行,当然,它会失败,因为存在至少包含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', async (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

© www.soinside.com 2019 - 2024. All rights reserved.