command.js中随机生成的字符串函数在e2e loginTest.js-Cypress中无法识别



我在下面复制了这段代码,并将其保存在我的support/command.js中。我正在使用以下函数创建多个用户名,以便使用CypressJS进行登录。

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+ '@gmail.com'

});

然后,在我的登录测试中。Spec,我称之为

const {commands} = require('../support/commands')
const { Input } = require("@angular/core")
const { wrap } = require("module")
const { isExportSpecifier } = require("typescript")

describe('our first suite', () => {
it('first test', () => {
cy.visit('/')
cy.get('a[data-tracking-name="Sign up for free"]').click()
cy.get('.flex').should('contain',"Create your free account")
cy.get('[for="emailSignup"]').should('contain',"Work email")
// cy.get('#emailSignup').type(generate_random_string(5))
cy.generate_random_string(5).then(random => {
cy.get('#emailSignup').type(random)
})
// cy.get('#emailSignup').type("John18002@gmail.com")
cy.contains('button', 'Continue').click()
cy.get('#fullName').type('IamTest User')
cy.get('#password').type('AHJQ*234')
cy.get('[type="submit"]').click()
cy.window().then((win) =>  {
cy.stub(win,'alert').as('alert')

})
cy.get('.flex').contains('Close').click()

})
})

我收到generate_random_string未定义的消息。我尝试在上面的函数支持下创建一个新文件,并尝试在commands.js中导入,然后在loginSpec文件中使用它,但即使这样也不起作用。使用基于网络的自动化工具几乎6年后,我不确定我做错了什么。非常感谢你的帮助。

TLDR是自定义命令,其返回值的方式与函数不同。

如果你想像这个一样使用它

cy.get('#emailSignup').type(generate_random_string())

那么它应该是一个简单的函数,而不是一个自定义命令。

const 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 + '@gmail.com'
}

如果你想把它作为一个自定义命令,可以像这个一样使用

cy.generate_random_string(10).then(random => {
cy.get('#emailSignup').type(random)
})

最新更新