如何使用 TypeScript 为 Cypress 设置自定义命令?

问题描述 投票:0回答:1

我用yarn开始了一个新项目,并添加了TypeScript和cypress作为依赖项。我使用自定义命令创建了一个示例测试。测试位于文件

cypress/e2e/cypress/example.cy.ts
中,内容为:

describe('Example', () => {
        it('example', () => {
                cy.myCommand();
        })
})

命令位于

cypress/e2e/cypress/support/commands.ts
中,内容为:

Cypress.Commands.add('myCommand', () => {
        cy.visit('https://example.cypress.io')
})

当我在 Cypress 中运行此命令时,我的测试失败并出现以下错误:“cy.myCommand 不是函数”。如何正确配置我的测试?

我使用的是赛普拉斯 13.6.5。

typescript cypress
1个回答
0
投票

当您添加 cypress 和 TypeScript 作为依赖项时,您不会自动拥有正确的配置。通过结合一些类似的答案,我找到了以下解决方案:

  • cypress/e2e/cypress/support/e2e.js
    重命名为
    cypress/e2e/cypress/support/e2e.ts
    。该文件仅导入命令。{js|ts}.

  • 更新

    commands.ts
    如下:

    declare namespace Cypress {
        interface Chainable<Subject = any> {
            myCommand(): Chainable<any>;
        }
    }
    
    Cypress.Commands.add('myCommand', () => {
        cy.visit('https://example.cypress.io')
    })
    
  • cypress.config.js
    重命名为
    cypress.config.ts
    (在项目的根目录中)。

  • 将以下行添加到

    cypress.config.ts

    supportFile: 'cypress/e2e/cypress/support/e2e.ts'
    
© www.soinside.com 2019 - 2024. All rights reserved.