install
npm install @playwright/test electron-playwright-helpers --save-dev
config
// playwright.config.ts
{
testDir: './tests', // 测试文件所在文件夹
use: {
browserName: 'chromium'
}
}
cli
npx playwright test
or
// package.json
{
// ...
"scripts": {
// ...
"test": "playwright test"
},
// ...
}
npm run test
test
import { test, expect, ElectronApplication, _electron as electron, Page } from '@playwright/test'
import { findLatestBuild } from 'electron-playwright-helpers'
import path from 'path'
let app: ElectronApplication
let page: Page
test.beforeAll(async () => {
const build = await findLatestBuild('dist_electron')
app = await electron.launch({
executablePath: path.join(build, 'SymbolMaker.exe')
})
app.on('window', async (page) => {
page.on('pageerror', async (error) => {
console.log(error)
})
page.on('console', async (message) => {
console.log(message.text())
})
})
page = await app.firstWindow()
await page.goto('app://./main.html') // 入口
await page.screenshot({ path: 'test-results/screenshot.png' })
})
test.afterAll(async () => {
await app.close()
})
test('app title should be Cool App', async () => {
const title = await page.$eval('.title', (el: HTMLElement) => el.textContent)
expect(title).toBe('Cool App')
})
test('打开 按钮存在', async () => {
const button = await page.getByRole('button', { name: '打开' })
expect(button).toBeDefined()
})
mocking native method
test('打开 按钮点击弹出文件选择器', async () => {
const svgPath = path.join(__dirname, 'resource', '1.svg')
app.evaluate(
async ({ dialog }, filePaths) => {
dialog.showOpenDialog = () => Promise.resolve({ canceled: false, filePaths })
},
[svgPath]
)
const button = await page.getByRole('button', { name: '打开' })
await button.click()
await page.screenshot({ path: 'test-results/screenshot2.png' })
})