这个例子非常接近我需要的,除了urls提前不知道(不能对它们进行硬编码)。
它们是通过运行脚本在挂钩urls中生成的:before()
before(() => {
cy.exec(<run script that generates a temporary urls.json file>);
cy.readFile("./urls.json")....
});
Run Code Online (Sandbox Code Playgroud)
我如何根据生成的动态生成单独的测试urls.json?
他们需要单独测试的原因是这样的。
测试枚举器在挂钩.forEach()之前运行before(),但如果您确切知道需要处理多少个网址,那就没问题。
在您引用的 Cypress 示例中,在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)
...
})
})
})
Run Code Online (Sandbox Code Playgroud)
注意,url不能再出现在测试描述中,但索引可以。
如果 url 数量未知,通过将测试枚举器设置为最大值,技术上仍然是可行的,但日志中的结果很混乱。未使用的测试槽仍显示为通过。
基本问题是生成器脚本需要在 Cypress Node 进程中运行,但规范在浏览器进程中运行。
但是浏览器和节点之间的 ipc 通信是通过cy.*只能在回调中运行的异步命令完成的,而回调只能在执行阶段运行。
您最好在外部运行生成器脚本,例如
"scripts": {
"gen:test": "npm run generator & cypress open"
}
Run Code Online (Sandbox Code Playgroud)
然后使用简单的方法require()来获取数据
"scripts": {
"gen:test": "npm run generator & cypress open"
}
Run Code Online (Sandbox Code Playgroud)