热血前端勇闯自动化测试 Playwright + TypeScript 如何debug以及如何使用Cookie


如何下载Playwright以及使用VScode插件运行测试用例

前言

问:前端做好好的为什么要来卷测试呢?
答:因为所有主线流程测试可能不会完全兼顾得到,所以为了能更(yu)好(kuai)的工(mo)作(yu),所以内心就产生了一个邪恶的想法😈假如我提测前把所有的主流程跑一边呢? so 请看下文(默认已经安装和了解Playwright了)


提示:以下是本篇文章正文内容,系好安全带 准备发车!

一、如何在运行中debug呢?

  1. 找到我们下载的PlayWright插件(如何下载请上滑开始部分)
    在这里插入图片描述

  2. ( 1. 点击你想要debug的代码块左侧,会出现小红点
    ( 2. 也可以在代码中添加debugger
    然后鼠标悬浮到该条测试用例上会出现小瓢虫的图标点击
    在这里插入图片描述

  3. 代码运行到你debug的地方就会停止了,左侧你会看到当前测试用例方法的执行上下文的内容
    在这里插入图片描述

  4. 以下图中标注了debug中的操作
    在这里插入图片描述

二、如何使用上下文的Cookie

由于系统使用的登录流程为前端输入账号密码登录=>后端验证setCookie,前端每次请求接口会带着具有登录态的Cookie请求来验证是否登录,所以每次自动化操作的时候需要登录

  1. 创建tests/auth.setup.ts
import { test as setup } from '@playwright/test'

const adminFile = 'auth/login.json'
setup('authenticate as login', async ({ page }) => {
  // Perform authentication steps. Replace these actions with your own.
  await page.goto(`http://xxx.com/login`)
  // 获取当前页面placeholder为账号的input并输入账号
  await page.getByPlaceholder('账号').fill('你的账号')
  // 获取当前页面placeholder为账号的input并输入密码
  await page.getByPlaceholder('密码').fill('密码')
  // 获取html标签为button并且文本为登录的按钮点击登录
  await page.getByRole('button', { name: '登录' }).click()
  // Wait until the page receives the cookies.
  //
  // Sometimes login flow sets cookies in the process of several redirects.
  // Wait for the final URL to ensure that the cookies are actually set.
  // 等待登录完成跳转的页面请求完毕
  await page.waitForURL('http://xxxx.com/')
  // Alternatively, you can wait until the page reaches a state where all cookies are set.
  // await expect(page.getByRole('button', { name: 'View profile and more' })).toBeVisible()

  // End of authentication steps.
  await page.context().storageState({ path: adminFile })
})
  1. 此时会生成 auth/login.json文件 里面就是后端set的Cookie
    在这里插入图片描述
  2. 在playwright.config.ts中添加配置
    use中添加:storageState: ‘auth/login.json’,
    projects中添加: { name: ‘setup’, testMatch: /.*.setup.ts/ },
import { defineConfig, devices } from '@playwright/test';

/**
 * Read environment variables from file.
 * https://github.com/motdotla/dotenv
 */
// require('dotenv').config();

/**
 * See https://playwright.dev/docs/test-configuration.
 */
export default defineConfig({
  testDir: './tests',
  /* Run tests in files in parallel */
  fullyParallel: true,
  /* Fail the build on CI if you accidentally left test.only in the source code. */
  forbidOnly: !!process.env.CI,
  /* Retry on CI only */
  retries: process.env.CI ? 2 : 0,
  /* Opt out of parallel tests on CI. */
  workers: process.env.CI ? 1 : undefined,
  /* Reporter to use. See https://playwright.dev/docs/test-reporters */
  reporter: 'html',
  /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
  use: {
    /* Base URL to use in actions like `await page.goto('/')`. */
    baseURL: '',
    storageState: 'auth/login.json',
    /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
    trace: 'on-first-retry',
  },

  /* Configure projects for major browsers */
  projects: [
    { name: 'setup', testMatch: /.*\.setup\.ts/ },
    {
      name: 'chromium',
      use: {
        ...devices['Desktop Chrome'],
        // storageState: 'auth/login.json',
      },
      // dependencies: ['setup'],
    },

    {
      name: 'firefox',
      use: { ...devices['Desktop Firefox'] },
    },

    {
      name: 'webkit',
      use: { ...devices['Desktop Safari'] },
    },

    /* Test against mobile viewports. */
    // {
    //   name: 'Mobile Chrome',
    //   use: { ...devices['Pixel 5'] },
    // },
    // {
    //   name: 'Mobile Safari',
    //   use: { ...devices['iPhone 12'] },
    // },

    /* Test against branded browsers. */
    // {
    //   name: 'Microsoft Edge',
    //   use: { ...devices['Desktop Edge'], channel: 'msedge' },
    // },
    // {
    //   name: 'Google Chrome',
    //   use: { ...devices['Desktop Chrome'], channel: 'chrome' },
    // },
  ],

  /* Run your local dev server before starting the tests */
  // webServer: {
  //   command: 'npm run start',
  //   url: 'http://127.0.0.1:3000',
  //   reuseExistingServer: !process.env.CI,
  // },
});

在这里插入图片描述

  1. 在测试用例中使用
    demo.spec.ts
test('demo', async ({ browser }) => {
  // 使用上下文的cookie
  const context = await browser.newContext({
    storageState: 'auth/login.json'
  })
  // 使用上下文创建page
  const page = await context.newPage()
  // 此时cookie就已经挂载上了
  await page.goto('http://xxxx.com');
  await page.getByRole('button', { name: '创建' }).click();
})
  • 16
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值