[英]How to reuse a function from an existing Cypress test, and call it in a new one?
I have the following function, which is inside a parent function. 我有以下函数,它在父函数中。
function generate_random_string(string_length) { // A function that creates a random string and will later pass this to a variable
let random_string = '';
let random_ascii;
for(let i = 0; i < string_length; i++) {
random_ascii = Math.floor((Math.random() * 25) + 97);
random_string += String.fromCharCode(random_ascii)
}
return random_string
}
var random_string = generate_random_string(6)
I have many uses for this random string generator, inside of other test files for different scenarios. 对于不同情况的其他测试文件,此随机字符串生成器有很多用途。 Instead of having to copy and paste this each time, I want to reuse this function and call it inside another test file.
无需每次都复制和粘贴此函数,我想重用此函数并在另一个测试文件中调用它。
How should I set this up? 我应该如何设置?
I tried to create a custom command inside the commands.js
file like so: 我试图在
commands.js
文件内创建一个自定义命令,如下所示:
Cypress.Commands.add("random_string_gen",
function generate_random_string(string_length) {
let random_string = '';
let random_ascii;
for(let i = 0; i < string_length; i++) {
random_ascii = Math.floor((Math.random() * 25) + 97);
random_string += String.fromCharCode(random_ascii)
}
return random_string
})
But this didn't work when I called it inside my test file: 但这在我在测试文件中调用它时不起作用:
cy.get('#name').click()
cy.get('#name').random_string_gen()
I want to reuse the function inside one file, and call it inside another, but I am not sure how to set up the necessary command/index JS files, so a template to get me started would be really helpful! 我想在一个文件内重用该函数,然后在另一个文件内调用它,但是我不确定如何设置必要的命令/索引JS文件,因此让我入门的模板真的很有帮助!
Just create a custom command on your cypress/support/commands.js
like this: 只需在
cypress/support/commands.js
上创建一个自定义命令,如下所示:
Cypress.Commands.add('generate_random_string', (string_length) => {
let random_string = '';
let random_ascii;
for(let i = 0; i < string_length; i++) {
random_ascii = Math.floor((Math.random() * 25) + 97);
random_string += String.fromCharCode(random_ascii)
}
return random_string
});
Then, on your test spec files you can call cy.generate_random_string(5)
. 然后,在测试规范文件上,可以调用
cy.generate_random_string(5)
。
For example, this will print to the console a random generated string with a length of 5. 例如,这将在控制台上打印一个长度为5的随机生成的字符串。
/// <reference types="Cypress" />
context('stackoverflow', () => {
it('stackoverflow', () => {
cy.generate_random_string(5).then((result) => {
console.log(result);
});
})
})
// Output: eauyy
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.