如何在赛普拉斯中检查电子邮件验证

时间:2020-07-17 12:29:21

标签: cypress e2e-testing

我想检查输入元素的有效性。我可以检查输入中是否输入了错误或有效的电子邮件格式。 这样。

 cy.get('#email_signup').type(validateEmail())
         var email = "";
            var possible = "abcd@.gh";
            for (var i = 0; i < 10; i++)
            email += possible.charAt(Math.floor(Math.random() * possible.length));
            return email;
        }

        cy.get('.nextBtn').click();
        cy.get('.error-message').should('be.visible');

2 个答案:

答案 0 :(得分:3)

首先,生成随机电子邮件是很好的,但是最好的方法是将一组电子邮件排列在一个数组中。 (可能以JSON格式)并遍历它们并检查电子邮件的有效性。

例如:

{
"Email_1":"['robot@mail.com','valid']",
"Email_2":"['robotmail.com','InValid']",
}

因为这样您便知道要测试的电子邮件条件。但是,如果您想使用随机电子邮件生成方法。我完全同意Muditha Perera的回答。效果很好。

答案 1 :(得分:0)

根据您的期望,您需要两个外部函数来创建电子邮件并获得电子邮件的有效状态。然后,您需要在所有电子邮件中循环使用 it 钩子。

//Create Emails
//Did a small modification so that you can decied the email length you need
const emails = (val) => {
var email = "";
var possible = "abcd@.gh";
for (var i = 0; i < val; i++){
email += possible.charAt(Math.floor(Math.random() * possible.length));}
return email;
}


//validate emails
//I have used a general Regex here, use the regex you have used in your website insted

const validateEmail = (email) => {
var re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
return re.test(email);
}

//Test Cases (I have added 10 loops so it will create 10 test cases)
//Change the test case count as much as you need
for (let index = 0; index < 10; index++) {
const TestEmail = emails(10)
const EmailState = validateEmail(TestEmail)
it("EmailTest -"+ TestEmail +" - " + EmailState,() => {
cy.get('#email_signup').type(TestEmail)
cy.get('.nextBtn').click();
    if(!EmailState){
         cy.get('.error-message').should('be.visible');
    }else{
         cy.get('.error-message').should('not.be.visible');
    }
})
}

您创建电子邮件的方法很棒。但是请确保添加单独的测试以检查特定和有效的情况,因为随机电子邮件可能无法覆盖所有情况

这就是测试的样子。

enter image description here

注意:如前所述。最好了解您的测试数据。因此,没有随机生成。尝试获取具有真实错误条件的有效,无效电子邮件方案的列表,并循环遍历它们。