Back to All Questions
Question 84 of 100
Debugging
Intermediate
How can you capture console logs?
The Answer
Listen to the `console` event on the `page` object to capture all browser console output, including logs, warnings, and errors.
Deep Dive Explanation
Capturing console errors is a powerful zero-cost quality check. Many real bugs (failed API calls, JavaScript errors) show up as console errors but don't visually break the UI. Adding a console error assertion to every test catches these silent failures automatically.
example.spec.ts
test('capture all console output', async ({ page }) => {
const logs: string[] = [];
const errors: string[] = [];
// Listen BEFORE navigating
page.on('console', msg => {
if (msg.type() === 'error') {
errors.push(`ERROR: ${msg.text()}`);
} else {
logs.push(`[${msg.type()}] ${msg.text()}`);
}
});
page.on('pageerror', err => {
errors.push(`Uncaught: ${err.message}`);
});
await page.goto('/app');
await page.getByRole('button', { name: 'Load Data' }).click();
// Assert no console errors
expect(errors).toEqual([]);
console.log('Console output:', logs.join('\n'));
});