An example of using @global-cache/playwright for cached authentication in the Playwright tests.
This approach is more efficient than the dependency project, because authentication is performed on-demand and doesn't require extra project in your config.
test/auth.spec.ts- tests for authenticated pagetest/no-auth.spec.ts- tests for non-authenticated pagetest/helpers/fixtures.ts- overwritesstorageStatefixture to lazily perform autheticationtest/helpers/auth.ts- authentication helper
When running all tests with 2 workers, authentication performed only in one worker (where it's really needed):
npx playwright test
Output:
Running 3 tests using 2 workers
✓ 1 test/no-auth.spec.ts:5:5 › no-auth test @no-auth (2.0s)
✘ 2 test/auth.spec.ts:4:5 › test 1 (4.6s)
Performing sing-in...
Worker 1, user is NOT authenticated.
Worker 0, user is authenticated.
✘ 3 test/auth.spec.ts:11:5 › test 2 (1.8s)
Worker 2, user is authenticated.
When running only no-auth test, authentication is skipped and test runs faster:
npx playwright test no-auth.spec.ts
Output:
Running 1 test using 1 worker
✓ 1 test/no-auth.spec.ts:5:5 › no-auth test @no-auth (2.1s)
Worker 0, user is NOT authenticated.
When running on 2 shards, authentication is performed only on one shard:
Shard 1:
npx playwright test --shard=1/2
Output:
Running 2 tests using 1 worker, shard 1 of 2
✘ 1 test/auth.spec.ts:4:5 › test 1 (4.3s)
Performing sing-in...
Worker 0, user is authenticated.
✘ 2 test/auth.spec.ts:11:5 › test 2 (2.0s)
Worker 1, user is authenticated.
Shard 2:
npx playwright test --shard=2/2
Output:
Running 1 test using 1 worker, shard 2 of 2
✓ 1 test/no-auth.spec.ts:5:5 › no-auth test @no-auth (2.3s)
Worker 0, user is NOT authenticated.