docs: add chrome extension testing example (#14969)

This commit is contained in:
Kaspar Emanuel 2022-07-07 19:28:01 +01:00 committed by GitHub
parent 105768fa38
commit 413258bfac
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -94,3 +94,57 @@ def run(playwright):
with sync_playwright() as playwright:
run(playwright)
```
## Testing
To have the extension loaded when running tests you can use a test fixture to set the context. You can also dynamically retrieve the extension id and use it that to load and test the popup page for example.
```typescript
import { test as base, expect, chromium, BrowserContext } from "@playwright/test";
import path from "path";
export const test = base.extend<{
context: BrowserContext;
extensionId: string;
}>({
context: async ({ browserName }, use) => {
const browserTypes = { chromium };
const pathToExtension = path.join(__dirname, "my-extension");
const context = await browserTypes[browserName].launchPersistentContext("", {
headless: false,
args: [
`--disable-extensions-except=${pathToExtension}`,
`--load-extension=${pathToExtension}`,
],
});
await use(context);
await context.close();
},
extensionId: async ({ context }, use) => {
/*
// for manifest v2:
let [background] = context.backgroundPages()
if (!background)
background = await context.waitForEvent("backgroundpage")
*/
// for manifest v3:
let [background] = context.serviceWorkers();
if (!background)
background = await context.waitForEvent("serviceworker");
const extensionId = background.url().split("/")[2];
await use(extensionId);
},
});
test("example test", async ({ page }) => {
await page.goto("https://example.com");
await expect(page.locator("body")).toHaveText("Changed by my-extension");
});
test("popup page", async ({ page, extensionId }) => {
await page.goto(`chrome-extension://${extensionId}/popup.html`);
await expect(page.locator("body")).toHaveText("my-extension popup");
});
```