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

Viewed 595

I'm trying to run assertions inside Puppeteer's page.on('response') event, however, the following error is thrown and the test wrongly passes: UnhandledPromiseRejectionWarning: AssertionError.

I've read that returning a promise should do the trick, but how can I resolve the promise if I don't know when the event will stop being emitted?

Here is the complete example code:

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/');
    });
});
1 Answers

You can have an array at the outer scope of page.on to fill with black-listed URLs and then wait for page.goto to finish page loading using page.goto waitUntil options and assert the array length at the end of the page load. You can even use that array to print the blacklisted URLs at the assertion message.

Please read inline comments

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')}`);
});

You'll get your test working without any exception errors and of course it will fail because there are response URLs containing tia at least:

Puppeteer Mocha assert test

Related