Cypress 命令相对于 vanilla 函数的优势是什么?

What is the advantage of Cypress commands over vanilla functions?

众所周知,在 Cypress 中我们可以在 commands.js 文件中定义 custom commands,语法如下:

Cypress.Commands.add('login', (email, pw) => {})
Cypress.Commands.overwrite('visit', (orig, url, options) => {})

这些命令将在我们所有的测试中变得可用,并且可以从 cy 对象中使用。

cy.login('my@email.com', '123456')
cy.visit('www.whosebug.com', 'www.google.com', { redirect: true })

但我不明白其中的要点。当您只需编写一个常规函数时,这样做有什么意义?

function login(email, pw) { /* ... */ }

login('my@email.com', '123456')

我看到的唯一优势是无需 export/import 即可使该函数随处可用,但您也可以使用全局变量来做到这一点。是这样吗,还是我漏掉了什么?

是的,你是对的!目标是编写更清晰的代码和可用性。使用 自定义命令 您基本上可以以 cypress 命令的形式编写函数,而且您不必在测试套件中编写 import 语句。因此,您的测试套件文件保持统一和清洁。