puppeteer自动化测试

1、基础知识

  • puppeteer.launch() 创建浏览器实例
  • puppeteer.newPage() 创建一个新页面
  • puppeteer.goto() 进入指定网站
  • page.screenshot() 截屏
  • page.pdf() 输出为pdf 注意必须是headless=true
  • page.evaluate() 在浏览器中执行函数想到与在控制台执行函数 返回promise
  • page.waitFor(selectorOrFunctionOrTimeout[, options[, ...args]]) 等待 可以是等待一段时间,某个函数执行或某个DOM的出现
  • page.click(selector[, options]) 点击某个元素
  • page.type(selector, text[, options]) 文本输入
  • page.frames() 获取当前页面所有的 iframe,然后根据 iframe 的名字精确获取某个想要的 iframe
  • iframe.$(‘.srchsongst‘) 获取 iframe 中的某个元素
  • iframe.evaluate() 在浏览器中执行函数,相当于在控制台中执行函数,返回一个 Promise
  • Array.from 将类数组对象转化为对象
  • iframe.$eval() 相当于在 iframe 中运行 document.queryselector 获取指定元素,并将其作为第一个参数传递
  • iframe.$$eval 相当于在 iframe 中运行 document.querySelectorAll 获取指定元素数组,并将其作为第一个参数传递
  • page.emulate() 指定设备

2、配置文件

jest.config.js
module.exports = {

    preset: 'jest-puppeteer', //调用preset
    // globals: _.assign({}, config.get('e2e'), { //这里可以注入全局变量
    //     ENV_URL: config.get('baseUrl')
    // }),
    testMatch: ['**/test/*.test.js?(x)'] //指定需要进行测试的文件
}
jest-puppeteer.config.js
const port = process.env.TEST_SERVER_PORT ?
    Number(process.env.TEST_SERVER_PORT) :
    4444

    // console.log(port)

process.env.TEST_SERVER_PORT = port

module.exports = {
    exitOnPageError: false,//false忽略错误,true捕获错误(default)
    launch: {
        headless: process.env.CI === 'true',
    },
    browserContext: process.env.INCOGNITO ? 'incognito' : 'default',
    server: {
        command: `cross-env PORT=${port} node test`,
        port,
        launchTimeout: 100000,
    },
}
命令行 npm run test
 "test": "cross-env INCOGNITO=true jest -c jest.config.js --notify --detectOpenHandles",

 3、服务文件/test/index.js(static即测试文件)

const path = require('path')
const express = require('express')

const app = express()

app.use(express.static(path.join(__dirname, 'static')))
console.log(process.env.PORT)

app.listen(process.env.PORT)

 参考文章

https://jestjs.io/docs/en/using-matchers
原文地址:https://www.cnblogs.com/yiyi17/p/10705931.html