12

我在我的cypress/support/commands.js文件中创建了以下自定义命令。

Cypress.Commands.add("login", (username, password) => {
    cy.request({
        method: 'POST',
        form: true,
        url: '/test/login/',
        body: {'username': username, 'password': password}
    })
})

在将登录功能移至此自定义命令之前,我已通过测试并登录工作。我在我的规范中使用 调用它cy.login(testuser, testpwd),但我收到以下错误消息TypeError: cy.login is not a function文档说/cypress/support/commands.js在评估任何测试文件之前已加载,因此我假设只需在其中放置自定义命令即可使该命令可用。我正在通过本地(GUI)测试运行程序运行测试。

4

5 回答 5

17

中的所有代码和引用的模块index.js都在您的测试文件之前加载。所以你需要commands.js在你的index.js文件中引用(要求)。但是,您可以直接在测试文件中导入commands.js模块,但是您需要在每个测试文件中包含它。推荐的方法是将它包含在index.js文件中,您不必担心在测试文件中明确引用。

于 2017-12-08T04:18:21.377 回答
7

要扩展@Dinesh Kumar 的出色答案,同样重要的是,您没有cypress.json通过添加以下行禁用对默认支持文件(我知道,在这种情况下是不幸的命名方案)的支持:supportFile: false

如果该行存在,请从您的行中删除cypress.json。如果您不喜欢使用cypress/support/index.js.

使用 commands.js 文件工作 index.js - 都在support文件夹中:

// index.js
const customCommands = require('./commands.js')

module.exports = {
  commands: customCommands
}

并仔细检查您的设置:

// cypress.json
{
  "baseUrl": "http://demo.your-domain.test",
  "supportFile": false,  // <-- delete this line present
  ...
}
于 2018-08-20T16:02:59.997 回答
1

将一条线import './commands.js'放入index.js.

于 2020-02-20T13:13:57.053 回答
0

对我来说,当我添加时它起作用了

declare namespace Cypress {
  interface Chainable {
    clearLocalStorageIframe(): void
  }
}

我正在使用 7.2.0 Cypress 和command.ts文件index.ts扩展名我已将其更改为 .ts

于 2021-05-15T14:31:26.567 回答
0

TL;DR:检查您的 IDE 是否尝试解决cy

我陷入了这个问题,因为我的 IDE 的自动完成功能添加了一个依赖项来解析未声明的cy对象——该对象由 cypress 注入。

const { default: cy } = require('date-fns/esm/locale/cy/index.js');

这是非常不幸的,因为自定义命令一直存在(2022 年)问题,您可以找到大量提示。

于 2022-02-25T14:32:03.667 回答