Playwright测试Electron项目

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' })
})
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容