我们如何从 Cypress 测试中调用一个写在单独文件中的函数?

How will we call a function written in a separate file from a Cypress test?

在 Cypress.io 测试中,我调用了一个减法函数,并在 'example-spec' 中编写了测试,如下所示。这工作正常。但是我们如何调用在不同的 js 文件中编写的相同减法函数,例如来自 Cypress 测试的 '/basetest.js'?

describe ('Calling a function', function(){
it('Call the Subtract function and asert the calculation', function(){
    cy
    .wrap({sub: subValues})
    .invoke('sub', 15, 8)
    .should('eq', 7) // true        
    })

})

// 减法函数:

const subValues = (a, b) => {
  return a - b 
}

Cypress 包含一个外部库文件,默认位于 (path to project)/support/index.js

该文件包含在所有测试文件中,因此您可以将共享代码放在这里。


您还可以在 support 文件夹中包含其他文件,在 index.js 中使用以下代码:

import './MySupportFile.js'

当包含外部测试文件时,简单的函数定义似乎无法继承。我不确定为什么。将函数插入 cy 对象对我有用:

cy.myFunction = greeting => {
    console.log(greeting);
};

cy.myNamespace = {};

cy.myNamespace.myNamespacedFunction = () => {
    console.log("hi");
};

cy 对象中的这些函数将转移到您拥有的任何 /integration 文件中。

来自https://docs.cypress.io/api/cypress-api/custom-commands.html

将此放入您的 support/commands.js 文件中:

Cypress.Commands.add('subValues', (a, b) => { return a - b });

将其放入您的 support/index.js 文件中,如果它不存在(应该存在):

import "./commands";

在你的测试中像这样调用它:

describe ('Calling a function', function(){
  it('Call the Subtract function and asert the calculation', function(){
    cy
      .subValues(15, 8)
      .should('eq', 7) // true        
    });
});

cypress/support/ 添加一个新文件,例如cypress/support/functions.js

cy.myproject = {
    makeUniqueUsername: () => {
        return 'cypress-test-' + Cypress.moment().format("YYMMDD-HHmmss");
    }
}

通过在 cypress/support/index.js

中添加对它的引用来包含它
import './functions'

然后从任何测试中调用您的函数

describe('registration', function() {
    it('can register', function() {
        let username = cy.myproject.makeUniqueUsername();
        cy.visit('/register');
        cy.get('#username').type(username);
        // etc...
    })
});

在考虑普通函数与 cypress“自定义命令”时请注意 cypress documentation encourage plain functions where custom commands aren't necessary in single spec files,尽管我不同意他们不应该 DRY 测试代码的观点。


感谢其他回答让我得到这个。 主要的添加是逐步实现,并将自定义函数保留在全局 cy.* 命名空间之外。


注意: 通过这种方式而不是通过 Cypress.Commands.add 注册命令,您将失去 Cypress UI 中的日志记录和时间旅行。 (感谢@conny)。这取决于您和您的团队,您对每种情况、明确的步骤或使用普通 js 的 IDE/linter/etc 支持更看重。注册命令使其成为测试中的显式步骤,而不仅仅是支持功能。