2024.09 前端自动化测试实践

2024-07-07  本文已影响0人  wo不是黄蓉

前端自动化测试

单元测试:Vitest/jtest

自动化测试工具选择:playwright/cypress

我们的项目分为移动端和管理端的,移动端用的公司统一的框架,技术是vue3+vite,管理端项目一般用的是webpack+vue2因此移动端技术选项优先考虑使用vitest,接下来我也会从使用的角度讲下为什么选择vitestplayright

实践:

我的项目移动端vue3+vite

单元测试-项目接入:

npm install -D vitest

vite.config.js defineConfig增加以下配置

  test: {
    // 使用浏览器的环境来替代node.js
    environment: 'jsdom',
    // 使用全局API
    globals: true,
    // 设置别名,可以在项目中使用@/xxx来查找路径
    alias: {
      '@': path.resolve(__dirname, 'src')
    }
    // 热更新
    // watch: false
  }

src下任意地方新建xx.spec.js/ts文件,执行npx vitest或者在package.json中配置scripts执行npm run test命令就可以自动执行以下用例了,接下来就可以写单元测试用例了,以下是一些例子

  "scripts": {
    "test": "vitest",
  },
// my first test
import { expect, test } from 'vitest'
import Cache from '@/views/ai/cache'

// 验证cache是否生效,describe-是一个藐视
describe('valid cache', () => {
  // 测试设置和获取items
  test('test setItem and getItem is OK', async () => {
    const cache = new Cache()
    cache.setItem('test', { msgType: 'text', content: 'hello' })
    const result = await cache.getItem('test')
    expect(result).toEqual(JSON.stringify({ msgType: 'text', content: 'hello' }))
  })

  // 测试获取所有项目
  test('test getAllItems  is OK', async () => {
    const cache = new Cache()
    cache.setItem('test', { msgType: 'text', content: 'hello' })
    cache.setItem('test1', { msgType: 'text1', content: 'hello1' })
    const result = await cache.getAllItems()
    expect(result).toEqual([
      { msgType: 'text', content: 'hello' },
      { msgType: 'text1', content: 'hello1' }
    ])
  })

  // 测试删除-删除成功应该返回true/false
  test('测试删除', async () => {
    const cache = new Cache()
    cache.setItem('test', { msgType: 'text', content: 'hello' })
    cache.removeItem('test')
    const result = await cache.getItem('text')
    expect(result).toEqual('')
  })
})

执行结果如下:执行通过,执行不通过时有明显的提示信息,可以看到执行过程

image-20240708214557611.png image-20240708214645961.png

vitest可以进行操作dom,但是我们的项目由于技术做了封口,所有的依赖不允许进行自定义,只能依赖一个core的库,所以在接入dom测试的时候有些问题,会提示,这个报错是由于vite和解析vue插件的版本不匹配导致的,上面说了我们不推荐自己引入插件所以在我的项目没有使用vitest来做dom方面操作的测试。

image-20240708215605954.png

自动化测试-项目接入:

执行如下命令过程中会询问你

npm init playwright@latest

项目初始化后会生成以下文件

playwright.config.ts
package.json
package-lock.json
tests/
  example.spec.ts
tests-examples/
  demo-todo-app.spec.ts

playwright.config.ts文件如下,我去掉了几个浏览器的配置项

import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
    //test文件夹 
  testDir: './e2e',
  /* 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: 'http://127.0.0.1:3000',

    /* 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: 'chromium',
      use: { ...devices['Desktop Chrome'] },
    },
  ],
});

编写测试用例,有两种方法一个是在e2e的文件夹下面的xx.spec.ts文件中进行编写,这种方法和编写node程序思路类似,只不过需要按照特定的api进行操作dom和请求接口;

另一种方法:在目录的任意地方新建xx.js文件,我的还写在e2e文件夹下面,新建ai.js编写代码,编写思路一样,只不过使用{headless:false}配置可以打开浏览器,这样我们就能直观的看到执行过程

第一种:修改e2e文件夹下的example.spec.ts文件

import { test, chromium } from '@playwright/test'

/**
 * 点击报表数据能够出来数据
 */
test('点击报表数据能够出来数据', async ({ page }) => {
  const browser = await chromium.launch({ headless: false })
  const context = await browser.newContext()
  // 添加cookie,因为跳转页面需要登录才可以进行正常请求
  context.addCookies([
    {
      name: 'wyzdzjxhdnh',
      domain: 'xxx',
      path: '/',
      value:
        'xxx'
    },
    {
      name: 'wyandyy',
      domain: 'xxx',
      path: '/',
      value:
        'xxx'
    }
  ])
  // 跳转到ai页面
  await page.goto('http://localhost:5173/#/ai?siteCode=xxx')

  // 请求推荐接口
  const requestContext = context.request
  let response = await requestContext.post(
    `
https://xxx/robot/getWelcomeAndQuestionReply`,
    {
      data: { channel: '首页', robotCode: 'arrKRLjspQAzobETfnVgtDFIKKBtGT', siteCode: 'xxx' }
    }
  )
  const data = await response.json()
  console.log('response', data)
})

执行以下命令得到运行结果,相当于是得到了成功的第一步,接下去就可以针对接口、页面等进行不同的测试了

npx playwright test
image-20240708221155007.png

第二种:使用node命令执行node .\e2e\ai.js,会新打开一个浏览器,可以看到实现了,当访问http://127.0.0.1:5173/#/ai?siteCode=xxx页面时会跳转到登录页面

找到页面的登录按钮,点击登录按钮之后会自动重定向到http://127.0.0.1:5173/#/ai?siteCode=xxx页面

找到页面的换一换元素,点击换一换,发现下面推荐的信息变了,over👏 👏 👏

// import { test, expect, chromium  } from '@playwright/test';
const { chromium } = require('playwright')
;(async () => {
  const browser = await chromium.launch({
    headless: false
  })
  const context = await browser.newContext()
  
  const page = await browser.newPage()
  // console.log('page',page)
  // 跳转到ai页面
  await page.goto('http://127.0.0.1:5173/#/ai?siteCode=xxx')
  // 找到一键登录按钮然后登录
  await page.getByText('一键登录', { exact: true }).click()
  // 执行测试用例-点击报表数据能够出来数据
  clickReportData(page)
})()

// 点击报表数据能够出来数据
function clickReportData(page) {
  // TODO
  // 查找到推荐元素点击推荐元素
  page.locator(".change-btn-container").click()
  // 
}

image.png

默认推荐


image.png
上一篇 下一篇

猜你喜欢

热点阅读