mirror of
https://github.com/microsoft/playwright.git
synced 2025-06-26 21:40:17 +00:00
docs: add chrome extension testing example (#14969)
This commit is contained in:
parent
105768fa38
commit
413258bfac
@ -94,3 +94,57 @@ def run(playwright):
|
|||||||
with sync_playwright() as playwright:
|
with sync_playwright() as playwright:
|
||||||
run(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");
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user