Este guia explica como configurar e utilizar o Playwright Model Context Protocol (MCP) para gerar testes de forma interativa com a ajuda de modelos de IA.
- Visual Studio Code
- Node.js instalado
- Acesso à extensão GitHub Copilot ou similar
Crie um arquivo mcp.json
na pasta de configuração do VS Code:
Caminho: C:\Users\<SeuUsuário>\AppData\Roaming\Code\User\
Substitua <SeuUsuário>
pelo seu nome de usuário do Windows.
Exemplo: C:\users\diet\AppData\Roaming\Code\User\mcp.json
Conteúdo do arquivo:
{
"servers": {
"playwright": {
"command": "npx",
"args": [
"@playwright/mcp@latest"
],
"type": "stdio"
}
},
"inputs": []
}
Crie uma pasta .github
no seu projeto (se ainda não existir) e adicione um arquivo copilot-instructions.md
:
Conteúdo do arquivo:
## Instructions
You are a Playwright test generator and an expert in TypeScript, Frontend development, and Playwright end-to-end testing.
You are given a scenario and you need to generate a Playwright test for it.
If you're asked to generate or create a Playwright test, use the tools provided by the Playwright MCP server to navigate the site and generate tests based on the current state and site snapshots.
Do not generate tests based on assumptions. Use the Playwright MCP server to navigate and interact with sites.
Access page snapshot before interacting with the page.
Only after all steps are completed, emit a Playwright TypeScript test that uses @playwright/test based on message history.
When you generate the test code in the 'tests' directory, ALWAYS follow Playwright best practices.
When the test is generated, always test and verify the generated code using `npx playwright test` and fix it if there are any issues.
Certifique-se de que seu projeto tenha os seguintes arquivos corretamente configurados:
{
"name": "playwright-mcp",
"version": "1.0.0",
"description": "Playwright MCP tests",
"main": "index.js",
"scripts": {
"test": "playwright test"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@playwright/test": "^1.54.2"
}
}
import { defineConfig } from '@playwright/test';
export default defineConfig({
testDir: './tests',
timeout: 30000,
reporter: [['html', { open: 'never' }]],
use: {
headless: false,
viewport: { width: 1280, height: 720 },
ignoreHTTPSErrors: true,
video: 'on-first-retry',
screenshot: 'only-on-failure',
trace: 'on-first-retry',
},
});
- Abra o VS Code e inicie o Copilot
- Configure para usar como AGENT e selecione Claude 3.7 (recomendado)
- Cole o prompt de exemplo ou crie seu próprio cenário de teste
Generate a Playwright test for the following scenario:
Navigate to https://checklyhq.com
Find and click the "documentation" in the top navigation
Check that the URL is /docs
Search for "Playwright test suite"
Click the first search result regardless of its content
Check that the resulting URL is /docs/playwright-checks
Após a geração do teste, execute-o com:
npx playwright test
Para visualizar o relatório HTML gerado:
npx playwright show-report
Este é o teste que criamos para o cenário de navegar ao site do Checkly e pesquisar por "Playwright test suite":
import { test, expect } from '@playwright/test';
test('Navigate to Checkly website and find Playwright test suite documentation', async ({ page }) => {
// Step 1: Navigate to https://checklyhq.com
await page.goto('https://www.checklyhq.com');
// Verify we're on the Checkly homepage
await expect(page).toHaveTitle(/Checkly/);
// Step 2: Find and click "documentation" in the top navigation
// First, click the Resources dropdown
const resourcesButton = page.getByRole('button', { name: 'Resources' }).first();
await resourcesButton.click();
// Then click the Documentation link in the dropdown menu
const documentationLink = page.getByRole('link', { name: 'Documentation', exact: true });
await documentationLink.click();
// Step 3: Check that the URL is /docs
await expect(page).toHaveURL(/\/docs\//);
// Step 4: Search for "Playwright test suite"
// Click the search button
const searchButton = page.getByRole('button', { name: 'Search' });
await searchButton.click();
// Type in the search query
const searchBox = page.getByRole('searchbox', { name: 'Search' });
await searchBox.fill('Playwright test suite');
// Wait for search results to appear
await page.waitForTimeout(1000);
// Step 5: Click the first search result
const firstSearchResult = page.getByRole('option').first();
await firstSearchResult.click();
// Step 6: Check that the resulting URL is /docs/playwright-checks
await expect(page).toHaveURL(/\/docs\/playwright-checks/);
});
O teste demonstra vários conceitos importantes do Playwright:
- Navegação básica: Uso do método
page.goto()
para acessar URLs - Seletores baseados em role: Uso de
getByRole()
para localizar elementos por sua função na página - Assertivas de teste: Uso de
expect()
para verificar títulos e URLs - Interação com elementos: Cliques em botões e preenchimento de campos de busca
- Esperas inteligentes: Uso de
waitForTimeout()
para garantir que elementos estejam disponíveis
O Playwright permite gravar interações com o navegador para gerar código de teste:
npx playwright codegen https://www.exemplo.com
O Playwright executa testes em paralelo por padrão. Você pode configurar isso no arquivo playwright.config.ts
:
export default defineConfig({
// Outras configurações...
workers: 3, // Número de workers paralelos
fullyParallel: true, // Executa testes em arquivos diferentes em paralelo
});
Execute seus testes no modo UI para depuração interativa:
npx playwright test --ui
Configure múltiplos navegadores no arquivo playwright.config.ts
:
export default defineConfig({
projects: [
{ name: 'chromium', use: { browserName: 'chromium' } },
{ name: 'firefox', use: { browserName: 'firefox' } },
{ name: 'webkit', use: { browserName: 'webkit' } },
],
});
Para executar em um navegador específico:
npx playwright test --project=firefox
O Playwright pode ser facilmente integrado a pipelines de CI/CD. Exemplo de configuração para GitHub Actions:
name: Playwright Tests
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 18
- name: Install dependencies
run: npm ci
- name: Install Playwright browsers
run: npx playwright install --with-deps
- name: Run Playwright tests
run: npx playwright test
- uses: actions/upload-artifact@v3
if: always()
with:
name: playwright-report
path: playwright-report/
retention-days: 30
- Utilize seletores estáveis: prefira usar
getByRole()
,getByText()
,getByTestId()
em vez de seletores CSS - Se encontrar elementos ambíguos, use especificadores como
.first()
ou.nth(1)
- A geração de relatórios HTML está configurada por padrão
- O modo não-headless está ativado para que você possa ver o navegador em ação durante os testes
- Utilize assertivas explícitas para verificar o estado da página antes de prosseguir
- Agrupe testes relacionados usando o método
test.describe()
Se o teste falhar porque não consegue encontrar um elemento:
- Verifique se o seletor está correto usando o modo de depuração do Playwright
- Adicione uma espera explícita com
await page.waitForSelector()
- Use o Playwright Inspector para localizar o seletor correto
Se o teste falhar por timeout:
- Aumente o timeout no arquivo de configuração ou para um teste específico
- Verifique se há animações ou carregamentos lentos que precisam de mais tempo
- Use
await page.waitForLoadState('networkidle')
para esperar que o carregamento termine
Se ocorrerem erros durante a navegação:
- Verifique se o site está acessível
- Configure
ignoreHTTPSErrors: true
para sites com certificados inválidos - Verifique se há redirecionamentos que podem estar afetando o teste
PlaywrightMCP/
├── .github/
│ └── copilot-instructions.md
├── tests/
│ └── checkly-navigation.spec.ts
├── playwright-report/
│ └── index.html
├── test-results/
├── package.json
├── playwright.config.ts
└── ReadmePlaywrightMCP.md
- Documentação oficial do Playwright
- API Reference do Playwright
- Melhores práticas para testes E2E
- Exemplos de testes Playwright
- Comunidade Playwright no Discord
O Playwright com MCP (Model Context Protocol) oferece uma abordagem poderosa para criar e manter testes de interface do usuário confiáveis. A integração com ferramentas de IA como o GitHub Copilot permite gerar testes rapidamente, enquanto mantém a qualidade e a manutenibilidade do código.
Aproveite este guia para iniciar seus projetos de automação de testes e explore os recursos avançados do Playwright para melhorar a qualidade do seu software.