UI 自动化测试 (悲观的人总是正确的,乐观的人总是成功的)

101 阅读1分钟

Google 就开发了 Puppeteer,一个基于 Node.js 的自动化测试工具,它提供了通过开发者工具协议来控制 Chrome 的 API 接口。Puppeteer 在默认情况下以无头模式运行,但可以配置为在有头下运行的模式。Puppeteer 也可以通过预置或手工配置的方式和 Jest 结合使用。如果选择预置方式的话,相关的第三方库也可以通过 NPM 来安

yarn add jest-puppeteer -D        

jest.config.js 配置 preset

{
  "preset": "jest-puppeteer"
}
describe('百度测试', () => {
  beforeAll(async () => {
    await page.goto('https://www.baidu.com/');
  });

  it('标题应该是百度"', async () => {
    await expect(page.title()).resolves.toMatch('百度');
  });
});

跑上述测试,碰到报错 主要是本地的 jest 和 全局 Jest 版本不一致, 把 jest *** 改成 yarn jest *** 解决

bobbyhadz.com/blog/jest-t…

stackoverflow.com/questions/7…

**注意设置了 "preset": "jest-puppeteer" 后 需将所有的 testEnvironment 选项都干掉 **

 Test suite failed to run

    TypeError: Cannot read properties of undefined (reading 'testEnvironmentOptions')

最终配置 (具体参考了 www.sanity.io/guides/test…

jest.config.js

/*
 * For a detailed explanation regarding each configuration property, visit:
 * https://jestjs.io/docs/configuration
 */

module.exports = {
  "preset": "jest-puppeteer",

  collectCoverage: true,

  // The directory where Jest should output its coverage files
  coverageDirectory: "coverage",
  coverageProvider: "v8",

};

jest-puppeteer.config 用于启动测试浏览器

module.exports = {
    launch: { 
      headless: false, 
      slowMo: 30, // 这个是放慢的速度,若需要再测试浏览器登录下系统再测试,可以调高下这个慢速,登录鉴权后再测试
    } 
  }

测试文件 index.test.js

describe('百度测试', () =>{
    beforeAll(async () => {
        await page.goto('https://www.baidu.com/');
    });

    it('标题应该是百度"', async () => {
      await expect(page.title()).resolves.toMatch('百度33');
    });
  });

package.json 中相关包

{
  "name": "puppeteer",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "jest"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "jest": "^29.7.0"
  },
  "devDependencies": {
    "@types/node": "^20.11.0",
    "expect-puppeteer": "^9.0.2",
    "jest-environment-jsdom": "^29.7.0",
    "jest-puppeteer": "^9.0.2",
    "puppeteer": "^21.7.0",
    "puppeteer-core": "^21.7.0",
    "ts-node": "^10.9.2",
    "typescript": "^5.3.3"
  }
}