|
| 1 | +# Experimental test mode for Playwright |
| 2 | + |
| 3 | +### Prerequisites |
| 4 | + |
| 5 | +You have a Next.js project. |
| 6 | + |
| 7 | +### Install `@playwright/test` in your project |
| 8 | + |
| 9 | +```sh |
| 10 | +npm install -D @playwright/test |
| 11 | +``` |
| 12 | + |
| 13 | +### Optionally install MSW in your project |
| 14 | + |
| 15 | +[MSW](https://mswjs.io/) can be helpful for fetch mocking. |
| 16 | + |
| 17 | +```sh |
| 18 | +npm install -D msw |
| 19 | +``` |
| 20 | + |
| 21 | +### Update `playwright.config.ts` |
| 22 | + |
| 23 | +```javascript |
| 24 | +import { defineConfig } from 'next/experimental/testmode/playwright' |
| 25 | + |
| 26 | +export default defineConfig({ |
| 27 | + webServer: { |
| 28 | + command: 'npm dev -- --experimental-test-proxy', |
| 29 | + url: 'http://localhost:3000', |
| 30 | + }, |
| 31 | +}) |
| 32 | +``` |
| 33 | + |
| 34 | +### Use the `next/experimental/testmode/playwright` to create tests |
| 35 | + |
| 36 | +```javascript |
| 37 | +import { test, expect } from 'next/experimental/testmode/playwright' |
| 38 | + |
| 39 | +test('/product/shoe', async ({ page, next }) => { |
| 40 | + next.onFetch((request) => { |
| 41 | + if (request.url === 'http://my-db/product/shoe') { |
| 42 | + return new Response( |
| 43 | + JSON.stringify({ |
| 44 | + title: 'A shoe', |
| 45 | + }), |
| 46 | + { |
| 47 | + headers: { |
| 48 | + 'Content-Type': 'application/json', |
| 49 | + }, |
| 50 | + } |
| 51 | + ) |
| 52 | + } |
| 53 | + return 'abort' |
| 54 | + }) |
| 55 | + |
| 56 | + await page.goto('/product/shoe') |
| 57 | + |
| 58 | + await expect(page.locator('body')).toHaveText(/Shoe/) |
| 59 | +}) |
| 60 | +``` |
| 61 | + |
| 62 | +### Or use the `next/experimental/testmode/playwright/msw` |
| 63 | + |
| 64 | +```javascript |
| 65 | +import { test, expect, rest } from 'next/experimental/testmode/playwright/msw' |
| 66 | + |
| 67 | +test.use({ |
| 68 | + mswHandlers: [ |
| 69 | + rest.get('http://my-db/product/shoe', (req, res, ctx) => { |
| 70 | + return res( |
| 71 | + ctx.status(200), |
| 72 | + ctx.json({ |
| 73 | + title: 'A shoe', |
| 74 | + }) |
| 75 | + ) |
| 76 | + }), |
| 77 | + ], |
| 78 | +}) |
| 79 | + |
| 80 | +test('/product/shoe', async ({ page, msw }) => { |
| 81 | + msw.use( |
| 82 | + rest.get('http://my-db/product/boot', (req, res, ctx) => { |
| 83 | + return res.once( |
| 84 | + ctx.status(200), |
| 85 | + ctx.json({ |
| 86 | + title: 'A boot', |
| 87 | + }) |
| 88 | + ) |
| 89 | + }) |
| 90 | + ) |
| 91 | + |
| 92 | + await page.goto('/product/boot') |
| 93 | + |
| 94 | + await expect(page.locator('body')).toHaveText(/Boot/) |
| 95 | +}) |
| 96 | +``` |
0 commit comments