模块API

本文共--字 阅读约--分钟 | 浏览: -- Last Updated: 2022-07-07

Cypress 允许你将它视为一个 Node Module 来运行。这种使用方式可以使你更加灵活地定制测试行为。模块API支持如下两个命令:Cypress.run()Cypress.open()

挑选测试用例运行

1、安装依赖包

npm install globby --save-dev

npm install console.table --save-dev

npm install cypress --save-dev

2、在 cypresss/integration目录下创建测试文件

// cypresss/integration/first-spec.js
describe('第一个用例', () => {
  it('测试 Module API', () => {
    expect(1).to.equal(1);
  })

  it('测试 Module API 2', () => {
    expect(2).to.equal(2);
  })
})

// cypresss/integration/second-spec.js
describe('第二个用例', () => {
  it('测试 Module API', () => {
    expect(1).not.equal(2);
  })
})

// cypresss/integration/third-spec.js
describe('第三个用例', () => {
  it('测试 Module API', () => {
    expect(3).to.equal(3);
  })
})

3、建立 testPickRunSimple.js

const cypress = require('cypress'); // 模块API,运行 Node Module 的方式引入
const globby = require('globby'); // 用于模式匹配目录文件
const Promise = require('bluebird'); // 高性能的 Promise 库
require('console.table');

// 定义 待运行的测试用例,实际项目中可以从外部文件读入

const fileList = [
  './cypress/integration/first-spec.js',
  './cypress/integration/third-spec.js',
]

// 过滤是否是存在 fileList 中的测试用例
const filterCaseToRun = (filenames) => {
  const withFilters = filenames.map((filename) => ({
    filename,
    run: fileList.includes(filename) // 存在 fileList 中就是需要运行的测试用例
  })).filter(item => item.run);
  
  return withFilters;
}

// 定义执行用例的函数
const runOneSpec = (spec) => { // spec 就是 withFilters 中的项
  cypress.run({
    config: {
      video: false,
    },
    spec: spec.filename
  })
}

globby('./cypress/integration/*-spec.js')
.then(filterCaseToRun) // 得到一个当前所有匹配的文件数组,进行过滤
.then((specs) => {
  console.table('测试现在开始,仅允许 fileList 中的用例运行', specs);
  return Promise.mapSeries(specs, runOneSpec) // 顺序执行每一个匹配测试文件
})
.then((runResults) => {
  // 定制你的测试报告或者对测试结果进行处理
  const summary = runResults.map((oneRun) => oneRun.runs[0]).map((run) => ({
    spec: run.spec.name,
    tests: run.stats.tests,
    passes: run.stats.passes,
    failures: run.stats.failures
  }))

  console.table('测试结果一览', summary);
})