如何在Cypress.io中创建类似于Selenium扩展元素的可重用元素?

nip*_*777 2 automated-tests cypress

在Selenium中,可以扩展元素。这样就可以使用一组可重用的自定义元素进行测试。

例如,我们可以getText添加一个方法。

public static string GetText(this IWebDriver driver)
{
    return driver.FindElement(By.TagName("body")).Text;
}
Run Code Online (Sandbox Code Playgroud)

并按以下方式重复使用:

myElement.getText();

此示例在此处进行了详细说明:http : //www.vcskicks.com/selenium-extensions.php

有没有办法在Cypress.io中复制此行为?还是我们需要查询并调用相同的方法来获取数据?

Jen*_*ane 5

您可以使用简单的功能来完成此操作。例如,您可以将几个函数移到中utils.js

export const getByText = (text) => cy.contains(text)
Run Code Online (Sandbox Code Playgroud)

然后将这些方法导入您的规范文件。

import { getByText } from './utils'

it('finds the element', () => {
  getByText('Jane Lane')
})
Run Code Online (Sandbox Code Playgroud)

您也可以创建一个自定义命令,但是有时按照最佳实践中的说明,这不是必需的。