Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

30.1 KB
Raw Blame
/**
 * Copyright 2018 Google Inc. All rights reserved.
 * Modifications copyright (c) Microsoft Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { attachFrame } from '../config/utils';
import { browserTest as it, expect } from '../config/browserTest';
import fs from 'fs';

import type { BrowserContext } from 'playwright-core';

it('ST-001 should capture local storage', async ({ contextFactory }) => {
  const context = await contextFactory();
  const page1 = await context.newPage();
  await page1.route('**/*', route => {
    route.fulfill({ body: '<html></html>' }).catch(() => {});
  });
  await page1.goto('https://www.example.com');
  await page1.evaluate(() => {
    localStorage['name1'] = 'value1';
  });
  await page1.goto('https://www.domain.com');
  await page1.evaluate(() => {
    localStorage['name2'] = 'value2';
  });
  const { origins } = await context.storageState();
  expect(origins).toEqual([{
    origin: 'https://www.domain.com',
    localStorage: [{
      name: 'name2',
      value: 'value2'
    }],
  }, {
    origin: 'https://www.example.com',
    localStorage: [{
      name: 'name1',
      value: 'value1'
    }],
  }]);
});

it('ST-002 should set local storage', async ({ contextFactory, channel }) => {
  it.fixme(channel?.startsWith('msedge'), 'Network.clearBrowserCache sometimes stalls');

  const context = await contextFactory({
    storageState: {
      cookies: [],
      origins: [
        {
          origin: 'https://www.example.com',
          localStorage: [{
            name: 'name1',
            value: 'value1'
          }]
        },
      ]
    }
  });
  const page = await context.newPage();
  await page.route('**/*', route => {
    route.fulfill({ body: '<html></html>' }).catch(() => {});
  });
  await page.goto('https://www.example.com');
  const localStorage = await page.evaluate('window.localStorage');
  expect(localStorage).toEqual({ name1: 'value1' });

  // Now use setStorageState to replace the storage
  await context.setStorageState({
    cookies: [],
    origins: [
      {
        origin: 'https://www.example.com',
        localStorage: [{
          name: 'name2',
          value: 'value2'
        }]
      },
    ]
  });
  expect(context.pages()).toHaveLength(1);
  await page.goto('https://www.example.com');
  const localStorage2 = await page.evaluate('window.localStorage');
  expect(localStorage2).toEqual({ name2: 'value2' });

  await context.close();
});

it('ST-003 should report good error if the url is not valid', async ({ contextFactory }) => {
  const error = await contextFactory({
    storageState: {
      cookies: [],
      origins: [
        {
          origin: 'foo',
          localStorage: [{
            name: 'name1',
            value: 'value1'
          }]
        },
      ]
    }
  }).catch(e => e);
  expect(error.message).toContain('browser.newContext: Error setting storage state:');
  expect(error.message).toContain('foo');
});

it('ST-004 should round-trip through the file', async ({ contextFactory, channel }, testInfo) => {
  it.fixme(channel?.startsWith('msedge'), 'Network.clearBrowserCache sometimes stalls');

  const context = await contextFactory();
  const page1 = await context.newPage();
  await page1.route('**/*', route => {
    route.fulfill({ body: '<html></html>' }).catch(() => {});
  });
  await page1.goto('https://www.example.com');
  await page1.evaluate(async () => {
    localStorage['name1'] = 'value1';
    document.cookie = 'username=John Doe';

    await new Promise((resolve, reject) => {
      const openRequest = indexedDB.open('db', 42);
      openRequest.onupgradeneeded = () => {
        openRequest.result.createObjectStore('store', { keyPath: 'name' });
        openRequest.result.createObjectStore('store2');
      };
      openRequest.onsuccess = () => {
        const transaction = openRequest.result.transaction(['store', 'store2'], 'readwrite');
        transaction
            .objectStore('store')
            .put({ name: 'foo', date: new Date(0), null: null });
        transaction
            .objectStore('store2')
            .put(new TextEncoder().encode('bar'), 'foo');
        transaction.addEventListener('complete', resolve);
        transaction.addEventListener('error', reject);
      };
    });

    return document.cookie;
  });

  const path = testInfo.outputPath('storage-state.json');
  const state = await context.storageState({ path, indexedDB: true });
  const written = await fs.promises.readFile(path, 'utf8');
  expect(JSON.stringify(state, undefined, 2)).toBe(written);

  const checkContext = async (context: BrowserContext) => {
    const page = await context.newPage();
    await page.route('**/*', route => {
      route.fulfill({ body: '<html></html>' }).catch(() => {});
    });
    await page.goto('https://www.example.com');
    const localStorage = await page.evaluate('window.localStorage');
    expect(localStorage).toEqual({ name1: 'value1' });
    const cookie = await page.evaluate('document.cookie');
    expect(cookie).toEqual('username=John Doe');
    const idbValues = await page.evaluate(() => new Promise((resolve, reject) => {
      const openRequest = indexedDB.open('db', 42);
      openRequest.addEventListener('success', async () => {
        const db = openRequest.result;
        const transaction = db.transaction(['store', 'store2'], 'readonly');
        const request1 = transaction.objectStore('store').get('foo');
        const request2 = transaction.objectStore('store2').get('foo');

        const [result1, result2] = await Promise.all([request1, request2].map(request => new Promise((resolve, reject) => {
          request.addEventListener('success', () => resolve(request.result));
          request.addEventListener('error', () => reject(request.error));
        })));

        resolve([result1, new TextDecoder().decode(result2 as any)]);
      });
      openRequest.addEventListener('error', () => reject(openRequest.error));
    }));
    expect(idbValues).toEqual([
      { name: 'foo', date: new Date(0), null: null },
      'bar'
    ]);
  };

  const context2 = await contextFactory({ storageState: path });
  await checkContext(context2);
  await context2.close();

  const context3 = await contextFactory();
  await context3.setStorageState(path);
  expect(context3.pages()).toHaveLength(0);
  await checkContext(context3);
  await context3.close();
});

it('ST-005 should round-trip OPFS', { annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/41400' } }, async ({ browserName, contextFactory, page, server }, testInfo) => {
  it.skip(browserName === 'webkit', 'OPFS is unavailable in non-persistent WebKit contexts');

  await page.goto(server.EMPTY_PAGE);
  await page.evaluate(async () => {
    const root = await navigator.storage.getDirectory();
    const nested = await root.getDirectoryHandle('nested', { create: true });
    await nested.getDirectoryHandle('empty', { create: true });

    const binary = await nested.getFileHandle('data.bin', { create: true });
    const binaryWritable = await binary.createWritable();
    await binaryWritable.write(new Uint8Array([0, 1, 2, 255]));
    await binaryWritable.close();

    const text = await root.getFileHandle('hello.txt', { create: true });
    const textWritable = await text.createWritable();
    await textWritable.write('Hello, world!');
    await textWritable.close();
  });

  expect(await page.context().storageState()).toEqual({ cookies: [], origins: [] });

  const path = testInfo.outputPath('storage-state.json');
  const storageState = await page.context().storageState({ path, opfs: true });
  expect(storageState.origins).toEqual([{
    origin: server.PREFIX,
    localStorage: [],
    opfs: [
      { path: 'hello.txt', type: 'file', base64: 'SGVsbG8sIHdvcmxkIQ==' },
      { path: 'nested', type: 'directory' },
      { path: 'nested/data.bin', type: 'file', base64: 'AAEC/w==' },
      { path: 'nested/empty', type: 'directory' },
    ],
  }]);
  expect(JSON.parse(await fs.promises.readFile(path, 'utf8'))).toEqual(storageState);
  expect(await page.context().request.storageState({ opfs: true })).toEqual(storageState);

  const checkContext = async (context: BrowserContext) => {
    expect(await context.storageState({ opfs: true })).toEqual(storageState);
    const checkPage = await context.newPage();
    await checkPage.goto(server.EMPTY_PAGE);
    expect(await checkPage.evaluate(async () => {
      const root = await navigator.storage.getDirectory();
      const hello = await (await root.getFileHandle('hello.txt')).getFile();
      const nested = await root.getDirectoryHandle('nested');
      const data = await (await nested.getFileHandle('data.bin')).getFile();
      const empty = await nested.getDirectoryHandle('empty');
      const emptyEntries = [];
      for await (const name of empty.keys())
        emptyEntries.push(name);
      return {
        text: await hello.text(),
        bytes: [...new Uint8Array(await data.arrayBuffer())],
        empty: emptyEntries,
      };
    })).toEqual({
      text: 'Hello, world!',
      bytes: [0, 1, 2, 255],
      empty: [],
    });
  };

  const context2 = await contextFactory({ storageState: path });
  await checkContext(context2);
  await context2.close();

  const context3 = await contextFactory();
  const page3 = await context3.newPage();
  await page3.goto(server.EMPTY_PAGE);
  await page3.evaluate(async () => {
    const root = await navigator.storage.getDirectory();
    await root.getFileHandle('stale.txt', { create: true });
  });
  await context3.setStorageState(storageState);
  await checkContext(context3);
  await context3.close();
});

it('ST-006 should capture cookies', async ({ server, context, page, contextFactory }) => {
  server.setRoute('/setcookie.html', (req, res) => {
    res.setHeader('Set-Cookie', ['a=b', 'empty=']);
    res.end();
  });

  await page.goto(server.PREFIX + '/setcookie.html');
  expect(await page.evaluate(() => {
    const cookies = document.cookie.split(';');
    return cookies.map(cookie => cookie.trim()).sort();
  })).toEqual([
    'a=b',
    'empty=',
  ]);

  const storageState = await context.storageState();
  expect(new Set(storageState.cookies)).toEqual(new Set([
    expect.objectContaining({
      name: 'a',
      value: 'b'
    }),
    expect.objectContaining({
      name: 'empty',
      value: ''
    })
  ]));
  const context2 = await contextFactory({ storageState });
  const page2 = await context2.newPage();
  await page2.goto(server.EMPTY_PAGE);
  expect(await page2.evaluate(() => {
    const cookies = document.cookie.split(';');
    return cookies.map(cookie => cookie.trim()).sort();
  })).toEqual([
    'a=b',
    'empty=',
  ]);
});

it('ST-007 should not emit events about internal page', async ({ contextFactory }) => {
  const context = await contextFactory();
  const page = await context.newPage();
  await page.route('**/*', route => {
    void route.fulfill({ body: '<html></html>' });
  });
  await page.goto('https://www.example.com');
  await page.evaluate(() => localStorage['name1'] = 'value1');
  await page.goto('https://www.domain.com');
  await page.evaluate(() => localStorage['name2'] = 'value2');

  const events = [];
  context.on('page', e => events.push(e));
  context.on('request', e => events.push(e));
  context.on('requestfailed', e => events.push(e));
  context.on('requestfinished', e => events.push(e));
  context.on('response', e => events.push(e));
  await context.storageState();
  expect(events).toHaveLength(0);
});

it('ST-008 should not restore localStorage twice', async ({ contextFactory }) => {
  const context = await contextFactory({
    storageState: {
      cookies: [],
      origins: [
        {
          origin: 'https://www.example.com',
          localStorage: [{
            name: 'name1',
            value: 'value1'
          }]
        },
      ]
    }
  });
  const page = await context.newPage();
  await page.route('**/*', route => {
    route.fulfill({ body: '<html></html>' }).catch(() => {});
  });
  await page.goto('https://www.example.com');
  const localStorage1 = await page.evaluate('window.localStorage');
  expect(localStorage1).toEqual({ name1: 'value1' });

  await page.evaluate(() => window.localStorage['name1'] = 'value2');

  await page.goto('https://www.example.com');
  const localStorage2 = await page.evaluate('window.localStorage');
  expect(localStorage2).toEqual({ name1: 'value2' });

  await context.close();
});

it('ST-009 should handle missing file', async ({ contextFactory }, testInfo) => {
  const file = testInfo.outputPath('does-not-exist.json');
  const error = await contextFactory({
    storageState: file,
  }).catch(e => e);
  expect(error.message).toContain(`Error reading storage state from ${file}:\nENOENT`);
});

it('ST-010 should handle malformed file', async ({ contextFactory, nodeVersion }, testInfo) => {
  const file = testInfo.outputPath('state.json');
  fs.writeFileSync(file, 'not-json', 'utf-8');
  const error = await contextFactory({
    storageState: file,
  }).catch(e => e);
  if (nodeVersion.major > 18)
    expect(error.message).toContain(`Error reading storage state from ${file}:\nUnexpected token 'o', \"not-json\" is not valid JSON`);
  else
    expect(error.message).toContain(`Error reading storage state from ${file}:\nUnexpected token o in JSON at position 1`);
});

it('ST-011 should serialize storageState with lone surrogates', async ({ page, context, server }) => {
  it.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright-dotnet/issues/2819' });
  await page.goto(server.EMPTY_PAGE);
  await page.evaluate(() => window.localStorage.setItem('foo', String.fromCharCode(55934)));
  const storageState = await context.storageState();
  expect(storageState.origins[0].localStorage[0].value).toBe(String.fromCharCode(55934));
});

it('ST-012 should work when service worker is intefering', async ({ page, context, server, isAndroid, isElectron, electronMajorVersion }) => {
  it.skip(isAndroid);
  it.skip(isElectron && electronMajorVersion < 30, 'error: Browser context management is not supported.');

  server.setRoute('/', (req, res) => {
    res.writeHead(200, { 'content-type': 'text/html' });
    res.end(`
      <script>
        console.log('from page');
        window.localStorage.foo = 'bar';
        window.registrationPromise = navigator.serviceWorker.register('sw.js');
        window.activationPromise = new Promise(resolve => navigator.serviceWorker.oncontrollerchange = resolve);
      </script>
    `);
  });

  server.setRoute('/sw.js', (req, res) => {
    res.writeHead(200, { 'content-type': 'application/javascript' });
    res.end(`
      const kHtmlPage = \`
        <script>
          console.log('from sw page');
          let counter = window.localStorage.counter || 0;
          ++counter;
          window.localStorage.counter = counter;
          setTimeout(() => {
            window.location.href = counter + '.html';
          }, 0);
        </script>
      \`;

      console.log('from sw 1');
      self.addEventListener('fetch', event => {
        console.log('fetching ' + event.request.url);
        const blob = new Blob([kHtmlPage], { type: 'text/html' });
        const response = new Response(blob, { status: 200 , statusText: 'OK' });
        event.respondWith(response);
      });

      self.addEventListener('activate', event => {
        console.log('from sw 2');
        event.waitUntil(clients.claim());
      });
    `);
  });

  await page.goto(server.PREFIX);
  await page.evaluate(() => window['activationPromise']);

  const storageState = await context.storageState();
  expect(storageState.origins[0].localStorage[0]).toEqual({ name: 'foo', value: 'bar' });
});

it('ST-013 should work when service worker is intefering and the origin is not open', async ({ page, context, server, isAndroid, isElectron, electronMajorVersion }) => {
  it.skip(isAndroid);
  it.skip(isElectron && electronMajorVersion < 30, 'error: Browser context management is not supported.');
  it.info().annotations.push({ type: 'issue', description: 'https://github.com/microsoft/playwright/issues/42656' });

  server.setRoute('/', (req, res) => {
    res.writeHead(200, { 'content-type': 'text/html' });
    res.end(`
      <script>
        window.localStorage.foo = 'bar';
        window.registrationPromise = navigator.serviceWorker.register('sw.js');
        window.activationPromise = new Promise(resolve => navigator.serviceWorker.oncontrollerchange = resolve);
      </script>
    `);
  });

  server.setRoute('/sw.js', (req, res) => {
    res.writeHead(200, { 'content-type': 'application/javascript' });
    res.end(`
      const kHtmlPage = \`
        <script>
          window.localStorage.fromServiceWorker = 'yes';
          window.location.href = 'redirected.html';
        </script>
      \`;

      self.addEventListener('fetch', event => {
        if (new URL(event.request.url).pathname !== '/')
          return;
        const blob = new Blob([kHtmlPage], { type: 'text/html' });
        event.respondWith(new Response(blob, { status: 200, statusText: 'OK' }));
      });

      self.addEventListener('activate', event => {
        event.waitUntil(clients.claim());
      });
    `);
  });

  server.setRoute('/redirected.html', (req, res) => {
    res.writeHead(200, { 'content-type': 'text/html' });
    res.end('<html></html>');
  });

  await page.goto(server.PREFIX);
  await page.evaluate(() => window['activationPromise']);
  await page.goto('about:blank');

  const storageState = await context.storageState();
  expect(storageState.origins[0].localStorage).toEqual([{ name: 'foo', value: 'bar' }]);
});

it('ST-014 should set local storage in third-party context', async ({ contextFactory, server }) => {
  const context = await contextFactory({
    storageState: {
      cookies: [],
      origins: [
        {
          origin: server.CROSS_PROCESS_PREFIX,
          localStorage: [{
            name: 'name1',
            value: 'value1'
          }]
        },
      ]
    }
  });
  const page = await context.newPage();
  await page.goto(server.EMPTY_PAGE);
  const frame = await attachFrame(page, 'frame1', server.CROSS_PROCESS_PREFIX + '/empty.html');

  const localStorage = await frame.evaluate('window.localStorage');
  expect(localStorage).toEqual({ name1: 'value1' });
  await context.close();
});

it('ST-015 should roundtrip local storage in third-party context', async ({ page, contextFactory, server }) => {
  await page.goto(server.EMPTY_PAGE);
  const frame = await attachFrame(page, 'frame1', server.CROSS_PROCESS_PREFIX + '/empty.html');
  await frame.evaluate(() => window.localStorage.setItem('name1', 'value1'));
  const storageState = await page.context().storageState();

  const context2 = await contextFactory({ storageState });
  const page2 = await context2.newPage();
  await page2.goto(server.EMPTY_PAGE);
  const frame2 = await attachFrame(page2, 'frame1', server.CROSS_PROCESS_PREFIX + '/empty.html');

  const localStorage = await frame2.evaluate('window.localStorage');
  expect(localStorage).toEqual({ name1: 'value1' });
  await context2.close();
});

it('ST-016 should support IndexedDB', async ({ page, server, contextFactory }) => {
  await page.goto(server.PREFIX + '/to-do-notifications/index.html');

  await expect(page.locator('#notifications')).toMatchAriaSnapshot(`
    - list:
      - listitem: Database initialised.
  `);
  await page.getByLabel('Task title').fill('Pet the cat');
  await page.getByLabel('Hours').fill('1');
  await page.getByLabel('Mins').fill('1');
  await page.getByText('Add Task').click();
  await expect(page.locator('#notifications')).toMatchAriaSnapshot(`
    - list:
      - listitem: "Transaction completed: database modification finished."
  `);

  const storageState = await page.context().storageState({ indexedDB: true });
  expect(storageState.origins).toEqual([
    {
      origin: server.PREFIX,
      localStorage: [],
      indexedDB: [
        {
          name: 'toDoList',
          version: 4,
          stores: [
            {
              name: 'toDoList',
              autoIncrement: false,
              keyPath: 'taskTitle',
              records: [
                {
                  valueEncoded: {
                    id: 1,
                    o: [
                      { k: 'taskTitle', v: 'Pet the cat' },
                      { k: 'hours', v: '1' },
                      { k: 'minutes', v: '1' },
                      { k: 'day', v: '01' },
                      { k: 'month', v: 'January' },
                      { k: 'year', v: '2025' },
                      { k: 'notified', v: 'no' },
                      { k: 'binaryTitle', v: { ab: { b: 'UGV0IHRoZSBjYXQ=' } }, }
                    ]
                  },
                },
              ],
              indexes: [
                {
                  name: 'day',
                  keyPath: 'day',
                  multiEntry: false,
                  unique: false,
                },
                {
                  name: 'hours',
                  keyPath: 'hours',
                  multiEntry: false,
                  unique: false,
                },
                {
                  name: 'minutes',
                  keyPath: 'minutes',
                  multiEntry: false,
                  unique: false,
                },
                {
                  name: 'month',
                  keyPath: 'month',
                  multiEntry: false,
                  unique: false,
                },
                {
                  name: 'notified',
                  keyPath: 'notified',
                  multiEntry: false,
                  unique: false,
                },
                {
                  name: 'year',
                  keyPath: 'year',
                  multiEntry: false,
                  unique: false,
                },
              ],
            },
          ],
        },
      ],
    },
  ]);

  const context = await contextFactory({ storageState });
  expect(await context.storageState({ indexedDB: true })).toEqual(storageState);

  const recreatedPage = await context.newPage();
  await recreatedPage.goto(server.PREFIX + '/to-do-notifications/index.html');
  await expect(recreatedPage.locator('#task-list')).toMatchAriaSnapshot(`
    - list:
      - listitem:
        - text: /Pet the cat \\[Pet the cat\\]/
  `);

  expect(await context.storageState()).toEqual({ cookies: [], origins: [] });
});

for (const restore of ['newContext', 'setStorageState'] as const) {
  it(`ST-017 should roundtrip IndexedDB values and keys with ${restore}`, {
    annotation: [
      { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/42703' },
      { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/43418' },
    ],
  }, async ({ page, server, contextFactory }, testInfo) => {
    await page.goto(server.EMPTY_PAGE);
    await page.evaluate(() => new Promise<void>((resolve, reject) => {
      const request = indexedDB.open('collections', 1);
      request.onupgradeneeded = () => request.result.createObjectStore('store');
      request.onerror = () => reject(request.error);
      request.onsuccess = () => {
        const db = request.result;
        const transaction = db.transaction('store', 'readwrite');
        const store = transaction.objectStore('store');
        store.put(new Map([['mk', 'mv']]), 'map');
        store.put(new Set([1, 2]), 'set');
        store.put(0, 'zero');
        store.put(false, 'false');
        store.put('', 'empty');
        store.put(null, 'null');
        store.put(Infinity, 'infinity');
        store.put('first', 0);
        store.put('second', '');
        transaction.oncomplete = () => {
          db.close();
          resolve();
        };
        transaction.onerror = () => reject(transaction.error);
      };
    }));

    const path = testInfo.outputPath('storage-state.json');
    const storageState = await page.context().storageState({ indexedDB: true, path });
    const context = await contextFactory(restore === 'newContext' ? { storageState: path } : {});
    if (restore === 'setStorageState')
      await context.setStorageState(storageState);
    expect(await context.storageState({ indexedDB: true })).toEqual(storageState);

    const restoredPage = await context.newPage();
    await restoredPage.goto(server.EMPTY_PAGE);
    const entries = await restoredPage.evaluate(async () => {
      const db = await new Promise<IDBDatabase>((resolve, reject) => {
        const request = indexedDB.open('collections', 1);
        request.onerror = () => reject(request.error);
        request.onsuccess = () => resolve(request.result);
      });
      const transaction = db.transaction('store', 'readonly');
      const store = transaction.objectStore('store');
      transaction.oncomplete = () => db.close();
      const [keys, values] = await Promise.all([store.getAllKeys(), store.getAll()].map(request => new Promise<any[]>((resolve, reject) => {
        request.onsuccess = () => resolve(request.result);
        request.onerror = () => reject(request.error);
      })));
      return keys.map((key, i) => {
        const value = values[i];
        if (value instanceof Map)
          return [key, { map: [...value] }];
        if (value instanceof Set)
          return [key, { set: [...value] }];
        return [key, value];
      });
    });
    expect(entries).toEqual([
      [0, 'first'],
      ['', 'second'],
      ['empty', ''],
      ['false', false],
      ['infinity', Infinity],
      ['map', { map: [['mk', 'mv']] }],
      ['null', null],
      ['set', { set: [1, 2] }],
      ['zero', 0],
    ]);
  });
}

it('ST-018 should support empty indexedDB', { annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/35760' } }, async ({ page, server, contextFactory }) => {
  await page.goto(server.EMPTY_PAGE);
  await page.evaluate(() => new Promise<void>(resolve => {
    const openRequest = indexedDB.open('unused-db');
    openRequest.onsuccess = () => resolve();
    openRequest.onerror = () => resolve();
  }));
  const storageState = await page.context().storageState({ indexedDB: true });
  expect(storageState.origins).toEqual([{
    origin: server.PREFIX,
    localStorage: [],
    indexedDB: [{
      name: 'unused-db',
      version: 1,
      stores: [],
    }]
  }]);

  const context = await contextFactory({ storageState });
  expect(await context.storageState({ indexedDB: true })).toEqual(storageState);
});

it('ST-019 should not leave IndexedDB connections open', { annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/42258' } }, async ({ contextFactory, server }) => {
  const context = await contextFactory();
  const page = await context.newPage();
  await page.goto(server.EMPTY_PAGE);
  await page.evaluate(async () => {
    const openRequest = indexedDB.open('db', 1);
    openRequest.onupgradeneeded = () => openRequest.result.createObjectStore('store');
    await new Promise<void>((resolve, reject) => {
      openRequest.onsuccess = () => {
        const db = openRequest.result;
        const transaction = db.transaction('store', 'readwrite');
        transaction.objectStore('store').put('value', 'key');
        transaction.oncomplete = () => {
          db.close();
          resolve();
        };
        transaction.onerror = () => reject(transaction.error);
      };
      openRequest.onerror = () => reject(openRequest.error);
    });
  });

  const state = await context.storageState({ indexedDB: true });

  await page.evaluate(() => new Promise<void>((resolve, reject) => {
    const request = indexedDB.deleteDatabase('db');
    request.onsuccess = () => resolve();
    request.onerror = () => reject(request.error);
    request.onblocked = () => reject(new Error('deleteDatabase was blocked'));
  }));

  await context.setStorageState(state);
  expect(await context.storageState({ indexedDB: true })).toEqual(state);
});

it('ST-020 should round-trip WebAuthn credentials with storageState', async ({ contextFactory, server }) => {
  const context = await contextFactory();
  const credential = await context.credentials.create(server.HOSTNAME);

  // Credentials are opt-in, omitted by default.
  expect(await context.storageState()).toEqual({ cookies: [], origins: [] });

  const storageState = await context.storageState({ credentials: true });
  expect(storageState).toEqual({ cookies: [], origins: [], credentials: [credential] });

  // A fresh context seeded from the storage state holds the same credential and round-trips equal.
  const context2 = await contextFactory({ storageState });
  expect(await context2.credentials.get()).toEqual([credential]);
  expect(await context2.storageState({ credentials: true })).toEqual(storageState);
});

it('ST-021 setStorageState should replace credentials', async ({ contextFactory }) => {
  const ctxA = await contextFactory();
  const credA = await ctxA.credentials.create('a.example.com');
  const stateA = await ctxA.storageState({ credentials: true });

  const ctxB = await contextFactory();
  const credB = await ctxB.credentials.create('b.example.com');
  const stateB = await ctxB.storageState({ credentials: true });

  const context = await contextFactory({ storageState: stateA });
  expect(await context.credentials.get()).toEqual([credA]);

  // Replacing the storage state swaps in the new credentials.
  await context.setStorageState(stateB);
  expect(await context.credentials.get()).toEqual([credB]);

  // A storage state without credentials clears them.
  await context.setStorageState({ cookies: [], origins: [] });
  expect(await context.credentials.get()).toEqual([]);

  // Credentials can be installed again afterwards.
  await context.setStorageState(stateA);
  expect(await context.credentials.get()).toEqual([credA]);
});

it('ST-022 setStorageState should handle missing file', async ({ contextFactory }, testInfo) => {
  const context = await contextFactory();
  const file = testInfo.outputPath('does-not-exist.json');
  const error = await context.setStorageState(file).catch(e => e);
  expect(error.message).toContain(`Error reading storage state from ${file}`);
});