我不想一次又一次地编写登录和注销代码,是否可以在一个地方编写代码并在整个测试中调用该地方?

时间:2019-12-06 04:49:05

标签: cypress

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个,因为我想在测试中多次登录和注销。 但是问题是我必须一次又一次地编写此代码,我如何才能将此代码嵌入到函数中,并调用该函数来优化我的代码?

1 个答案:

答案 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();

您的登录方法说明: 通常,最好以编程方式登录,而不要单击按钮。考虑直接从赛普拉斯发送登录请求,而不是总是单击按钮进行登录。

相关问题