In this example we will explore how to sharing data in multiple test or spec files using import and export file in playwright. If you want to share data using export and import (i.e., through a shared module), you can do it within the same process, but Playwright runs globalSetup in a separate Node.js process, so any in-memory data (like a variable) won’t persist across to the test files.
However, for basic sharing within the same process (e.g., utility files or helper modules), here’s how it works — and why it won’t work the way you expect in globalSetup without a file or other persistence.
If you're trying to share a runtime state between multiple Playwright test files or modules using export/import, here's a clear breakdown of how your shared.ts file works and how to use it effectively:
shared.js — Shared State Container
// shared.js export const runtimeState = { value: null };
This exports a mutable object. Since JavaScript/TypeScript modules are singletons, when you import this object elsewhere, all imports will refer to the same instance. So you can safely use it to share state at runtime.
Example Usage in Playwright Test Files
test1.spec.js
// test1.spec.js import { test } from '@playwright/test'; import { runtimeState } from './shared'; test('set value', () => { runtimeState.value = 'hello from test1'; });
test2.spec.js
// test2.spec.js import { test } from '@playwright/test'; import { runtimeState } from './shared'; test('read value', () => { console.log(runtimeState.value); // ✅ Will log 'hello from test1' });
NOTE :
Playwright runs tests in parallel by default. This means:
test1.spec.js and test2.spec.js might not share state reliably unless you disable parallelism or run them in the same worker.
No comments:
Post a Comment