Reputation: 63
I want to run my mochajs front-end unit tests in a headless browser, specifically using puppeteer. So, following the very simple example on the mochajs
page here, I am running a basic unit test and am seeing mocha
's results and they are rendered in the page as they should be. I see that they would also be rendered to chromium's console
when I load the simple example in a real browser. All great. However, I want to return these results from the call to this script. How do I return these test results from running mochajs
in puppeteer
? In other words:
$ node my-script-running-mocha-in-puppeteer.js
Array
#indexOf()
✓ should return -1 when the value is not present
1 passing (9ms)
My code basically looks like this:
const puppeteer = require('puppeteer');
puppeteer.launch().then(async browser => {
const page = await browser.newPage();
await page.setContent(`
/*
HTML page with mocha, unit tests and source.
*/
`);
// Get page content
const content = await page.content();
// I see the mocha test result in the page but now I
// want to return them from this script.
console.log(content);
await browser.close();
});
Upvotes: 6
Views: 959
Reputation: 25230
As you are saying, that mocha is also printing the data into the console, this is likely the easiest way to get the test results.
To simply mirror the IO of the browser including any data logged to console, you can enable the option dumpio
when launching the browser:
puppeteer.launch({ dumpio: true })
Quote from the docs for puppeteer.launch
:
dumpio
<boolean
> Whether to pipe the browser process stdout and stderr intoprocess.stdout
andprocess.stderr
. Defaults tofalse
.
Be aware, that this will also print other information from the browser into the console. If you are looking only for the console data, you can use the second option.
console.log
, etc.To only get the data which is logged to console.log
or console.info
, etc. you can listen to the console
event.
page.on('console', consoleMessage => {
console.log(consoleMessage.text());
if (consoleMessage.type() === 'error') {
// handle error output
}
});
This way, you can grab all output going into the console. You can even use consoleMessage.type()
to differentiate between error, warnings and normal output.
Upvotes: 3