In Playwright, setting { auto: true } configures a custom fixture to execute automatically for every test—even if the test does not explicitly request it in its arguments.
To define an automatic fixture, pass a tuple [fixtureFunction, { auto: true }] inside test.extend().
1. Define the Automatic Fixture (fixtures.ts)
Here is a practical TypeScript example that automatically logs test execution time and captures uncaught page errors for every test:
import { test as base, expect } from '@playwright/test';
type AutoFixtures = {
autoLogger: void;
consoleErrorGuard: void;
};
export const test = base.extend<AutoFixtures>({
// Runs automatically before and after every test
autoLogger: [
async ({}, use, testInfo) => {
const startTime = Date.now();
console.log(`Starting: ${testInfo.title}`);
// Hand control over to the test (no value passed since it's void)
await use();
const duration = Date.now() - startTime;
console.log(`Finished: ${testInfo.title} (${duration}ms)`);
},
{ auto: true },
],
// Automatically monitors the 'page' fixture for uncaught JS errors
consoleErrorGuard: [
async ({ page }, use) => {
const errors: Error[] = [];
page.on('pageerror', (error) => errors.push(error));
await use();
// Fail the test during teardown if any uncaught errors occurred
expect(errors, `Uncaught page errors:\n${errors.join('\n')}`).toHaveLength(0);
},
{ auto: true },
],
});
export { expect };
2. Use It in Your Tests (example.spec.ts)
Import test from your custom fixtures.ts file instead of @playwright/test. Neither autoLogger nor consoleErrorGuard needs to be passed into the test callback:
import { test, expect } from './fixtures';
test('homepage loads without console errors', async ({ page }) => {
// autoLogger and consoleErrorGuard run automatically around this test
await page.goto('https://playwright.dev');
await expect(page).toHaveTitle(/Playwright/);
});
Key Details to Keep in Mind
- Tuple syntax. An automatic fixture must be wrapped in an array
[async ({}, use) => { ... }, { auto: true }]. - Empty
use()call. Because tests do not destructurevoidautomatic fixtures, callawait use()with no arguments. - Worker scope support. You can combine
auto: truewith{ scope: 'worker' }(i.e.,{ scope: 'worker', auto: true }) if you want setup/teardown logic to run automatically once per worker process instead of once per test. - Custom
testimport. Automatic fixtures only trigger in spec files that importtestfrom your extended fixture module.

No comments:
Post a Comment