describe('Cypress Test', () => {
before(async () => {});
// it 1
it('Navigating to login screen', () => {
cy.visit('localhost:4280/auth/login');
});
// it 2
it('should accept registered credentials', () => {
cy.get("input[id="username"]").clear().type("admin");
cy.get(story47Obj.btnLoginSubmit).click();
cy.get("input[id="password"]").clear().type("admin");
cy.get("button[id="submit"]").click();
});
// it 3
it('URL must include dashboard', () => {
cy.url({timeout: 5000}).should('include', '/dashboard')
});
// it 4
it('Test: should logout it', () => {
cy.get("button[id="logout"]").should('be.visible').click();
});
});
我必须一次又一次地写这4个它,因为我想在测试中多次登录和注销。 但是问题是我必须一次又一次地编写此代码,我如何才能将此代码嵌入到函数中,并调用该函数来优化我的代码?
答案 0 :(得分:1)
您可以在cypress/support/index.js
在您的情况下,它将是以下代码:
Cypress.Commands.add("it1", => {
cy.visit('localhost:4280/auth/login');
});
Cypress.Commands.add("it2", => {
cy.get("input[id="username"]").clear().type("admin");
cy.get(story47Obj.btnLoginSubmit).click();
cy.get("input[id="password"]").clear().type("admin");
cy.get("button[id="submit"]").click();
});
Cypress.Commands.add("it3", => {
cy.url({timeout: 5000}).should('include', '/dashboard')
});
Cypress.Commands.add("it4", => {
cy.get("button[id="logout"]").should('be.visible').click();
});
然后您可以像下面这样调用这些方法:
cy.it1();
cy.it2();
cy.it3();
cy.it4();
您的登录方法说明: 通常,最好以编程方式登录,而不要单击按钮。考虑直接从赛普拉斯发送登录请求,而不是总是单击按钮进行登录。