Warm tip: This article is reproduced from serverfault.com, please click

其他-如何基于“ before()”中接收到的数据动态生成赛普拉斯测试?

(其他 - How to dynamically generate Cypress tests based on data received in `before()`?)

发布于 2020-11-28 04:22:33

这个例子非常接近我所需要的,除了urls不提前知道(不能对它们进行硬编码)。

urls在生成的before()钩通过运行脚本:

before(() => {
  cy.exec(<run script that generates a temporary urls.json file>);
  cy.readFile("./urls.json")....
});

如何根据生成的内容动态生成单独的测试urls.json

他们需要进行单独测试的原因是这样的

Questioner
Misha Moroshko
Viewed
11
Richard Matsen 2020-11-29 03:26:30

测试枚举器.forEach()before()挂钩之前运行,但是如果你确切知道需要处理多少个URL,就可以了。

在你引用的Cypress示例中,在中设置了url before()

let urls = []; 

describe('Logo', () => {

  before(() => {
    cy.exec('npm run generator')
      .then(() => {  // writing the file will be async
        cy.readFile("./urls.json").then(data => {
          urls = data;
      });
    });
  })

  Cypress._.range(0, 2).forEach(index => {       // only need the number of tests here

    it(`Should display logo #${index}`, () => {
      const url = urls[index]                    // runs after before()
      cy.visit(url)
      ...
    })
  })
})

注意,url不能再出现在测试描述中,但是索引可以。

如果url的数量未知,从技术上讲,仍然可以通过将测试枚举数设置为最大值来实现,但是日志中的结果是混乱的。未使用的测试插槽仍显示为通过。


基本问题是生成器脚本需要在赛普拉斯节点进程中运行,但规范在浏览器进程中运行。

但是浏览器和节点之间的ipc通信是通过cy.*只能在回调中运行的异步命令完成的,该回调命令只能在执行阶段运行。

你最好从外部运行生成器脚本,例如

"scripts": {
  "gen:test": "npm run generator & cypress open"
}

然后使用简单的方法require()来收集数据

const data = require('./urls.json')
let urls = data.urls;
const testCount = data.urls.length;  

describe('Logo', () => {

  before(() => {
    // not required
  })

  Cypress._.range(0, testCount).forEach(index => {

  or

  urls.forEach((url, index) => {