赛普拉斯在多个测试套件中重用测试用例

use*_*993 2 testing automated-tests cypress

我是 Cypress 的新手,正在尝试一个 POC。

我正在开发的应用程序要求我在不同的测试套件中测试相同的组件。有什么原因可以避免重写相同的代码块,比如使用函数?

export function testWelcomeBanner() {
    ...
 welcomeBanner.should('have.text', 'welcome');
    ...
}
Run Code Online (Sandbox Code Playgroud)

我确实尝试了一些方法,例如尝试从测试套件中的块中调用此函数等,但收到错误。任何帮助表示赞赏。

Set*_*eth 12

Cypress 建议像使用普通的旧 JavaScript 一样使用函数。

...编写 Cypress 测试是 JavaScript,并且为可重复行为编写函数通常更有效。

来源

将可重用的函数放入单独的文件中。

utils.js

/// <reference types="cypress" />

export function testWelcomeBanner() {
  // Add more logic as needed here. You can also return
  // the result of your `cy.` call.
  cy.get("div.welcomeBanner")
    .should("have.text", "welcome");
}
Run Code Online (Sandbox Code Playgroud)

然后将这些函数导入您的 Cypress 测试中。

myTest.spec.js

/// <reference types="cypress" />
import { testWelcomeBanner } from "../utils.js"; // Adjust the path for your environment

describe("testing", () => {
  it("can do something", () => {
    ...
    testWelcomeBanner();
    ...
  });
});
Run Code Online (Sandbox Code Playgroud)


Ala*_*Das 5

您可以使用自定义命令来重复使用您的脚本。您可以从cypress docs阅读有关自定义命令的更多信息。

您可以在下面编写可重用的函数 cypress/support/command.js

Cypress.Commands.add('welcomeBanner', (text) => {
  cy.get('locator').should('have.text', 'text');
})
Run Code Online (Sandbox Code Playgroud)

您可以在任何测试中使用上述命令,例如

cy.welcomeBanner('Welcome Text')
Run Code Online (Sandbox Code Playgroud)