在自動化測試的領域中,Playwright 是一款由 Microsoft 開發的現代化 E2E 測試框架,支援多瀏覽器(Chromium、Firefox、WebKit)、多語言(JavaScript、TypeScript、Python、Java、.NET),非常適合用來測試 Web 應用。
今天我們就來簡單玩玩 Playwright,透過 TypeScript + VS Code 快速搭建一個測試環境,並實作一個基本案例:打開 Google,搜尋「study4」,點擊第一個搜尋結果,並驗證網址是否為 https://study4.tw。
開始之前:準備好你的環境
請先確保你已安裝以下工具:
- Node.js(建議版本 18 以上)
- Visual Studio Code
步驟一:建立專案
mkdir playwright-ts-demo
cd playwright-ts-demo
npm init -y
步驟二:安裝 Playwright 與 TypeScript 支援
npm install -D playwright typescript ts-node @types/node
Playwright 安裝後可以支援 Chromium、Firefox、WebKit 等瀏覽器的自動操作。
步驟三:建立 TypeScript 設定檔 tsconfig.json
{
"compilerOptions": {
"target": "ESNext",
"module": "CommonJS",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"outDir": "dist"
},
"include": ["src"]
}
步驟四:撰寫測試腳本
建立 src
資料夾,新增一個檔案 searchStudy4.ts
:
import { chromium } from 'playwright';
(async () => {
const browser = await chromium.launch({ headless: false }); // 顯示瀏覽器操作
const page = await browser.newPage();
await page.goto('https://www.google.com');
// 接受 Google cookie(若有出現)
const acceptButton = await page.$('text=接受所有');
if (acceptButton) await acceptButton.click();
// 輸入搜尋關鍵字並送出
await page.fill('input[name="q"]', 'study4');
await page.keyboard.press('Enter');
// 等待搜尋結果載入
await page.waitForSelector('h3');
// 點擊第一個搜尋結果
const firstResult = await page.locator('h3').first();
await firstResult.click();
// 等待跳轉完成
await page.waitForLoadState('load');
// 驗證網址
const url = page.url();
if (url.includes('study4.tw')) {
console.log('成功導向 study4.tw');
} else {
console.error(`導向錯誤,實際網址為:${url}`);
}
await browser.close();
})();
步驟五:執行測試
npx ts-node src/searchStudy4.ts
額外推薦 VS Code 套件
以下是開發 Playwright 時推薦安裝的 VS Code 套件:
- Playwright Test for VSCode:提供測試錄製、除錯、自動補全等功能。
- ESLint:強化 TypeScript 程式碼品質。
- Prettier:保持程式碼一致性。