如何在赛普拉斯规格中参数化文件名并加载该文件?我正在通过工作正常的环境变量注入其他参数,但是提供给require(...)
它的任何东西都不会作为文件找到(尽管错误消息以与硬编码完全相同的方式指定了文件名)。
describe('run test', () => {
const data = require('../fixtures/my.json');
it('foo', () {
...
});
因此,换句话说,上述片段的行为不同于:
describe('run test', () => {
const file = Cypress.env('file');
const data = require('../fixtures/' + file);
data.forEach((entry) => {
it(`foo testing ${entry}`, () {
... run a test based on `entry`
});
});
当通过命令行从命令行调用cypress时$(npm bin)/cypress run ... --env file=my.json
。在file
提供参数的示例中,显示未找到文件错误消息(具有与硬编码文件名示例相同的文件路径)。我相信这是因为它们require()
在运行时没有得到解决(但是之前并不能接受动态参数),但是我不是100%肯定,因此还会考虑使用一种替代方法来读取文件。
这是动态测试用例创建规范的基本结构。它由环境变量和文件的组合填充。环境变量中的元素ids
为各个测试用例的参数指定键,这些参数在单独的文件中提供(也通过环境变量指定)。在ids
被序列化并通过分隔外部脚本。
通过以下方式调用此脚本:
$(npm bin)/cypress run --config-file cypress.json --headless --env ids=foo@bar@blah,paramsFile=myParamfile.json
let paramsFile = Cypress.env('paramsFile');
let ids = Cypress.env('ids');
describe('My test', () => {
let params;
before(() => {
cy.task('readFileMaybe', paramsFile).then(fileContent => {
if (fileContent === null) {
throw new Error(`Could not find file ${paramsFile}.`);
}
// params = {id1: testcaseParam2, id2: testcaseParam2, ...}
// `testcaseParamX` are objects or arrays and can therefore not be passed
// easily into the test case via environment variables.
params = JSON.parse(fileContent);
});
});
// `ids` is a string -> needs to be split
// e.g. `ids.split(delim).forEach(...)` to actually run.
ids.forEach(id => {
// Create test case.
it(`test case for ${id}`, () => {
let param = params[id];
// run assertions here...
});
});
});
plugins/index.js
(参考)module.exports = (on, config) => {
on('task', {
// Needs to be done through a task, as we can't access `fs` in test case
// (this task runs in Node which allows use of external libraries).
readFileMaybe(filename) {
// console.log('Loading ', filename);
if (fs.existsSync(filename)) {
return fs.readFileSync(filename, 'utf8');
}
// console.log('Could not find ', filename);
return null;
}
});
};
开始工作非常痛苦。但是,直接在Node中的Cypress上下文外部运行命令的功能非常强大,并且也可以用于类似的问题。我希望其他人觉得这有用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句