【Playwright】playwright登陆认证

遇到的问题

使用playwright.config.ts中的dependencies配置项来进行其他用例的前置登陆

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// Setup project
    { name: 'setup', testMatch: /setup\.ts/ },
    {
      name: 'chromium',

      use: {
        ...devices['Desktop Chrome'],
        storageState: 'tests/.auth/zengdong.json',
      },
      dependencies: ['setup'],
    },

其中setup.ts的内容如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import { expect, test as setup } from '@playwright/test'
import path from 'path'

const authFile = path.join(__dirname, '../.auth/zengdong.json')

setup('authenticate', async ({ page }) => {
  // Perform authentication steps. Replace these actions with your own.
  await page.goto('/auth/login')
  await page.getByPlaceholder('请输入邮箱地址').fill('xxxxxxxx')
  await page.getByPlaceholder('请输入密码').fill('xxxxxx')
  await page.getByRole('button', { name: '登 录' }).click()
  // Wait until the page receives the cookies.
  await expect(page.getByText('登录成功')).toBeVisible()
  // Alternatively, you can wait until the page reaches a state where all cookies are set.

  await page.waitForURL('http://xxxxxxxxxx', {
    waitUntil: 'load',
  }) // End of authentication steps.
  await page.context().storageState({ path: authFile })
})

但是登陆页面的用例不需要前置登陆

解决方案

  • 登陆用例单独配置成一个 project,其他 project 忽略登陆用例
  • 登陆用例不使用 setup.ts 生成的 storageState
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import { AuthPage } from '../pages/authPage'
import { AllMonitorPage } from '../pages/allMonitorPage'
import { test as baseTest } from '@playwright/test'

export const test = baseTest.extend<{
  authPage: AuthPage
  allMonitorPage: AllMonitorPage
}>({
  authPage: async ({ browser, storageState }, use) => {
    // 👉 使用 test.use 传下来的 storageState 参数(默认或被覆盖)
    const context = await browser.newContext({
      storageState: undefined,
    })
    const page = await context.newPage()
    const authPage = new AuthPage(page)
    await use(authPage)
    await context.close()
  },
  allMonitorPage: async ({ page }, use) => {
    await use(new AllMonitorPage(page))
  },
})
Licensed under CC BY-NC-SA 4.0
comments powered by Disqus
使用 Hugo 构建
主题 StackJimmy 设计