Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
feat(test): make reuseContext public (#41858)
Pavel Feldman449349caea6d
diff --git a/docs/src/test-api/class-testoptions.md b/docs/src/test-api/class-testoptions.mdindex 8808b14ece..fbf8e9f24f 100644--- a/docs/src/test-api/class-testoptions.md+++ b/docs/src/test-api/class-testoptions.md@@ -480,6 +480,42 @@ export default defineConfig({});```+## property: TestOptions.reuseContext+* since: v1.62+* discouraged: This option trades test isolation for speed and is intended for component tests that drive a story gallery. Leave it unset for end-to-end tests - a fresh browser context per test is one of the core guarantees of Playwright Test.+- type: <[boolean]>++**Experimental.** When set to `true`, all tests in a worker process run in a single browser context that is reused between tests, instead of getting a brand new context per test. Defaults to `false`.++Between tests, Playwright resets the state that component tests typically touch: it clears cookies, cache, local storage and IndexedDB of visited origins, unregisters service workers, closes extra pages, removes routes, bindings and init scripts, and re-applies the configured storage state, viewport and emulation options.++This reset is best-effort, not a guarantee of isolation. State that is **not** reset includes:+* Permissions granted with [`method: BrowserContext.grantPermissions`] during a test.+* Runtime changes made through [`method: BrowserContext.setGeolocation`], [`method: BrowserContext.setOffline`] and [`method: BrowserContext.setExtraHTTPHeaders`].+* Browsing history, `window.name` and any browser-process-wide state.++Additional restrictions:+* The option is ignored when [`property: TestOptions.video`] recording is enabled.+* Only a few context options may differ between consecutive tests: `colorScheme`, `forcedColors`, `reducedMotion`, `contrast`, `screen`, `userAgent`, `viewport` and `testIdAttribute`. Changing any other option in [`method: Test.use`], for example `locale` or `storageState`, silently forces a fresh context and negates the speedup.+* Do not combine with [`property: TestOptions.connectOptions`] pointing multiple workers at a shared browser - workers would compete for the single reusable context.+* `recordHar` in [`property: TestOptions.contextOptions`] is not supported and produces no HAR file.++**Usage**++```js title="playwright.config.ts"+import { defineConfig } from '@playwright/test';++export default defineConfig({+ projects: [+ {+ name: 'components',+ testDir: './tests/components',+ use: { reuseContext: true },+ },+ ],+});+```+## property: TestOptions.screenshot* since: v1.10- type: <[Object]|[ScreenshotMode]<"off"|"on"|"only-on-failure"|"on-first-failure">>diff --git a/packages/playwright/src/index.ts b/packages/playwright/src/index.tsindex 34f9d6deda..7bb29dc0d2 100644--- a/packages/playwright/src/index.ts+++ b/packages/playwright/src/index.ts@@ -452,9 +452,11 @@ const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures, UtilityTestFixt_optionContextReuseMode: ['none', { scope: 'worker', option: true, box: true }],_optionConnectOptions: [undefined, { scope: 'worker', option: true, box: true }],- _reuseContext: [async ({ video, _optionContextReuseMode }, use) => {+ reuseContext: [false, { scope: 'worker', option: true, box: true }],++ _reuseContext: [async ({ video, _optionContextReuseMode, reuseContext }, use) => {let mode = _optionContextReuseMode;- if (process.env.PW_TEST_REUSE_CONTEXT)+ if (process.env.PW_TEST_REUSE_CONTEXT || reuseContext)mode = 'when-possible';const reuse = mode === 'when-possible' && normalizeVideoMode(video) === 'off';await use(reuse);diff --git a/packages/playwright/types/test.d.ts b/packages/playwright/types/test.d.tsindex 44d6742a8c..16d6d4d166 100644--- a/packages/playwright/types/test.d.ts+++ b/packages/playwright/types/test.d.ts@@ -6944,6 +6944,61 @@ export interface PlaywrightWorkerOptions {* [testOptions.channel](https://playwright.dev/docs/api/class-testoptions#test-options-channel) are ignored.*/connectOptions: ConnectOptions | undefined;+ /**+ * **NOTE** This option trades test isolation for speed and is intended for component tests that drive a story gallery. Leave+ * it unset for end-to-end tests - a fresh browser context per test is one of the core guarantees of Playwright Test.+ *+ * **Experimental.** When set to `true`, all tests in a worker process run in a single browser context that is reused+ * between tests, instead of getting a brand new context per test. Defaults to `false`.+ *+ * Between tests, Playwright resets the state that component tests typically touch: it clears cookies, cache, local+ * storage and IndexedDB of visited origins, unregisters service workers, closes extra pages, removes routes, bindings+ * and init scripts, and re-applies the configured storage state, viewport and emulation options.+ *+ * This reset is best-effort, not a guarantee of isolation. State that is **not** reset includes:+ * - Permissions granted with+ * [browserContext.grantPermissions(permissions[, options])](https://playwright.dev/docs/api/class-browsercontext#browser-context-grant-permissions)+ * during a test.+ * - Runtime changes made through+ * [browserContext.setGeolocation(geolocation)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-geolocation),+ * [browserContext.setOffline(offline)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-offline)+ * and+ * [browserContext.setExtraHTTPHeaders(headers)](https://playwright.dev/docs/api/class-browsercontext#browser-context-set-extra-http-headers).+ * - Browsing history, `window.name` and any browser-process-wide state.+ *+ * Additional restrictions:+ * - The option is ignored when+ * [testOptions.video](https://playwright.dev/docs/api/class-testoptions#test-options-video) recording is enabled.+ * - Only a few context options may differ between consecutive tests: `colorScheme`, `forcedColors`,+ * `reducedMotion`, `contrast`, `screen`, `userAgent`, `viewport` and `testIdAttribute`. Changing any other option+ * in [test.use(options)](https://playwright.dev/docs/api/class-test#test-use), for example `locale` or+ * `storageState`, silently forces a fresh context and negates the speedup.+ * - Do not combine with+ * [testOptions.connectOptions](https://playwright.dev/docs/api/class-testoptions#test-options-connect-options)+ * pointing multiple workers at a shared browser - workers would compete for the single reusable context.+ * - `recordHar` in+ * [testOptions.contextOptions](https://playwright.dev/docs/api/class-testoptions#test-options-context-options) is+ * not supported and produces no HAR file.+ *+ * **Usage**+ *+ * ```js+ * // playwright.config.ts+ * import { defineConfig } from '@playwright/test';+ *+ * export default defineConfig({+ * projects: [+ * {+ * name: 'components',+ * testDir: './tests/components',+ * use: { reuseContext: true },+ * },+ * ],+ * });+ * ```+ *+ */+ reuseContext: boolean;/*** Whether to automatically capture a screenshot after each test. Defaults to `'off'`.* - `'off'`: Do not capture screenshots.@@ -8673,7 +8728,6 @@ export function mergeExpects<List extends any[]>(...expects: List): MergedExpectexport { };-/*** The [APIResponseAssertions](https://playwright.dev/docs/api/class-apiresponseassertions) class provides assertion* methods that can be used to make assertions about thediff --git a/tests/playwright-test/playwright.reuse.spec.ts b/tests/playwright-test/playwright.reuse.spec.tsindex cba587545f..047ec35d29 100644--- a/tests/playwright-test/playwright.reuse.spec.ts+++ b/tests/playwright-test/playwright.reuse.spec.ts@@ -18,8 +18,13 @@ import { test, expect } from './playwright-test-fixtures';import { parseTrace } from '../config/utils';import fs from 'fs';+const withReuseContext = (files: Record<string, string>) => ({+ 'playwright.config.ts': `export default { use: { reuseContext: true } };`,+ ...files,+});+test('should reuse context', async ({ runInlineTest }) => {- const result = await runInlineTest({+ const result = await runInlineTest(withReuseContext({'src/reuse.test.ts': `import { test, expect } from '@playwright/test';let lastContextGuid;@@ -52,17 +57,17 @@ test('should reuse context', async ({ runInlineTest }) => {});});`,- }, { workers: 1 }, { PW_TEST_REUSE_CONTEXT: '1' });+ }), { workers: 1 });expect(result.exitCode).toBe(0);expect(result.passed).toBe(5);});test('should not reuse context with video if mode=when-possible', async ({ runInlineTest }, testInfo) => {- const result = await runInlineTest({+ const result = await runInlineTest(withReuseContext({'playwright.config.ts': `export default {- use: { video: 'on' },+ use: { video: 'on', reuseContext: true },};`,'src/reuse.test.ts': `@@ -77,7 +82,7 @@ test('should not reuse context with video if mode=when-possible', async ({ runInexpect(context._guid).not.toBe(lastContextGuid);});`,- }, { workers: 1 }, { PW_TEST_REUSE_CONTEXT: 'when-possible' });+ }), { workers: 1 });expect(result.exitCode).toBe(0);expect(result.passed).toBe(2);@@ -86,10 +91,10 @@ test('should not reuse context with video if mode=when-possible', async ({ runIn});test('should reuse context with trace if mode=when-possible', async ({ runInlineTest }, testInfo) => {- const result = await runInlineTest({+ const result = await runInlineTest(withReuseContext({'playwright.config.ts': `export default {- use: { trace: 'on' },+ use: { trace: 'on', reuseContext: true },};`,'reuse.spec.ts': `@@ -117,7 +122,7 @@ test('should reuse context with trace if mode=when-possible', async ({ runInlineawait page.locator('input').click();});`,- }, { workers: 1 }, { PW_TEST_REUSE_CONTEXT: 'when-possible' });+ }), { workers: 1 });expect(result.exitCode).toBe(0);expect(result.passed).toBe(2);@@ -160,7 +165,7 @@ test('should reuse context with trace if mode=when-possible', async ({ runInline});test('should work with manually closed pages', async ({ runInlineTest }) => {- const result = await runInlineTest({+ const result = await runInlineTest(withReuseContext({'src/button.test.ts': `import { test, expect } from '@playwright/test';@@ -182,14 +187,14 @@ test('should work with manually closed pages', async ({ runInlineTest }) => {await page.locator('button').click();});`,- }, { workers: 1 }, { PW_TEST_REUSE_CONTEXT: '1' });+ }), { workers: 1 });expect(result.exitCode).toBe(0);expect(result.passed).toBe(3);});test('should clean storage', async ({ runInlineTest }) => {- const result = await runInlineTest({+ const result = await runInlineTest(withReuseContext({'src/reuse.test.ts': `import { test, expect } from '@playwright/test';let lastContextGuid;@@ -226,13 +231,13 @@ test('should clean storage', async ({ runInlineTest }) => {expect(session).toBeFalsy();});`,- }, { workers: 1 }, { PW_TEST_REUSE_CONTEXT: '1' });+ }), { workers: 1 });expect(result.exitCode).toBe(0);expect(result.passed).toBe(2);});test('should restore localStorage', async ({ runInlineTest }) => {- const result = await runInlineTest({+ const result = await runInlineTest(withReuseContext({'src/reuse.test.ts': `import { test, expect } from '@playwright/test';let lastContextGuid;@@ -300,14 +305,14 @@ test('should restore localStorage', async ({ runInlineTest }) => {expect(local).toBe('anotherValue');});`,- }, { workers: 1 }, { PW_TEST_REUSE_CONTEXT: '1' });+ }), { workers: 1 });expect(result.exitCode).toBe(0);expect(result.passed).toBe(3);});test('should clean db', async ({ runInlineTest }) => {test.slow();- const result = await runInlineTest({+ const result = await runInlineTest(withReuseContext({'src/reuse.test.ts': `import { test, expect } from '@playwright/test';let lastContextGuid;@@ -340,13 +345,13 @@ test('should clean db', async ({ runInlineTest }) => {expect(dbnames).toEqual([]);});`,- }, { workers: 1 }, { PW_TEST_REUSE_CONTEXT: '1' });+ }), { workers: 1 });expect(result.exitCode).toBe(0);expect(result.passed).toBe(2);});test('should restore cookies', async ({ runInlineTest }) => {- const result = await runInlineTest({+ const result = await runInlineTest(withReuseContext({'src/reuse.test.ts': `import { test, expect } from '@playwright/test';let lastContextGuid;@@ -398,13 +403,13 @@ test('should restore cookies', async ({ runInlineTest }) => {expect(cookie).toBe('');});`,- }, { workers: 1 }, { PW_TEST_REUSE_CONTEXT: '1' });+ }), { workers: 1 });expect(result.exitCode).toBe(0);expect(result.passed).toBe(3);});test('should reuse context with beforeunload', async ({ runInlineTest }) => {- const result = await runInlineTest({+ const result = await runInlineTest(withReuseContext({'src/reuse.test.ts': `import { test, expect } from '@playwright/test';let lastContextGuid;@@ -422,14 +427,14 @@ test('should reuse context with beforeunload', async ({ runInlineTest }) => {expect(context._guid).toBe(lastContextGuid);});`,- }, { workers: 1 }, { PW_TEST_REUSE_CONTEXT: '1' });+ }), { workers: 1 });expect(result.exitCode).toBe(0);expect(result.passed).toBe(2);});test('should cancel pending operations upon reuse', async ({ runInlineTest }) => {- const result = await runInlineTest({+ const result = await runInlineTest(withReuseContext({'src/reuse.test.ts': `import { test, expect } from '@playwright/test';test('one', async ({ page }) => {@@ -446,7 +451,7 @@ test('should cancel pending operations upon reuse', async ({ runInlineTest }) =>expect(await page.evaluate('window._clicked')).toBe(undefined);});`,- }, { workers: 1 }, { PW_TEST_REUSE_CONTEXT: '1' });+ }), { workers: 1 });expect(result.exitCode).toBe(0);expect(result.passed).toBe(2);@@ -455,7 +460,7 @@ test('should cancel pending operations upon reuse', async ({ runInlineTest }) =>test('should reset tracing', async ({ runInlineTest }, testInfo) => {const traceFile1 = testInfo.outputPath('trace1.zip');const traceFile2 = testInfo.outputPath('trace2.zip');- const result = await runInlineTest({+ const result = await runInlineTest(withReuseContext({'reuse.spec.ts': `import { test, expect } from '@playwright/test';test('one', async ({ page }) => {@@ -472,7 +477,7 @@ test('should reset tracing', async ({ runInlineTest }, testInfo) => {await page.context().tracing.stopChunk({ path: ${JSON.stringify(traceFile2)} });});`,- }, { workers: 1 }, { PW_TEST_REUSE_CONTEXT: '1' });+ }), { workers: 1 });expect(result.exitCode).toBe(0);expect(result.passed).toBe(2);@@ -494,7 +499,7 @@ test('should reset tracing', async ({ runInlineTest }, testInfo) => {});test('should not delete others contexts', async ({ runInlineTest }) => {- const result = await runInlineTest({+ const result = await runInlineTest(withReuseContext({'src/reuse.test.ts': `import { test as base, expect } from '@playwright/test';const test = base.extend<{ loggedInPage: Page }>({@@ -508,17 +513,17 @@ test('should not delete others contexts', async ({ runInlineTest }) => {await loggedInPage.goto('data:text/plain,Hello world');});`,- }, { workers: 1 }, { PW_TEST_REUSE_CONTEXT: '1' });+ }), { workers: 1 });expect(result.exitCode).toBe(0);expect(result.passed).toBe(1);});test('should survive serial mode with tracing and reuse', async ({ runInlineTest }, testInfo) => {- const result = await runInlineTest({+ const result = await runInlineTest(withReuseContext({'playwright.config.ts': `import { defineConfig } from '@playwright/test';- export default defineConfig({ use: { trace: 'on' } });+ export default defineConfig({ use: { trace: 'on', reuseContext: true } });`,'reuse.spec.ts': `import { test, expect } from '@playwright/test';@@ -540,7 +545,7 @@ test('should survive serial mode with tracing and reuse', async ({ runInlineTestawait page.fill('input', 'value');});`,- }, { workers: 1 }, { PW_TEST_REUSE_CONTEXT: '1' });+ }), { workers: 1 });expect(result.exitCode).toBe(0);expect(result.passed).toBe(2);diff --git a/utils/generate_types/overrides-test.d.ts b/utils/generate_types/overrides-test.d.tsindex 713979b3bf..9adad0984d 100644--- a/utils/generate_types/overrides-test.d.ts+++ b/utils/generate_types/overrides-test.d.ts@@ -261,6 +261,7 @@ export interface PlaywrightWorkerOptions {channel: BrowserChannel | undefined;launchOptions: Omit<LaunchOptions, 'tracesDir'>;connectOptions: ConnectOptions | undefined;+ reuseContext: boolean;screenshot: ScreenshotMode | { mode: ScreenshotMode } & Pick<PageScreenshotOptions, 'fullPage' | 'omitBackground'>;trace: TraceMode | /** deprecated */ 'retry-with-trace' | { mode: TraceMode, snapshots?: boolean, screenshots?: boolean, sources?: boolean, attachments?: boolean };video: VideoMode | /** deprecated */ 'retry-with-video' | { mode: VideoMode, size?: ViewportSize, show?: { actions?: { duration?: number, position?: 'top-left' | 'top' | 'top-right' | 'bottom-left' | 'bottom' | 'bottom-right', fontSize?: number, cursor?: 'none' | 'pointer' }, test?: { level?: 'file' | 'title' | 'step', position?: 'top-left' | 'top' | 'top-right' | 'bottom-left' | 'bottom' | 'bottom-right', fontSize?: number } } };@@ -542,4 +543,3 @@ export function mergeExpects<List extends any[]>(...expects: List): MergedExpect// This is required to not export everything by default. See https://github.com/Microsoft/TypeScript/issues/19545#issuecomment-340490459export { };-