【问题标题】:Converting Cypress file into a more appropriate format for exporting将 Cypress 文件转换为更适合导出的格式
【发布时间】:2023-04-02 22:30:01
【问题描述】:

我正在努力将最佳实践付诸实践,将用于赛普拉斯测试的现有文件转换为更适合导出和导入的格式。

目前:

支持文件.js

export const1 = () => cy.get('#someId1');
export const2 = () => cy.get('#someId2');
export const3 = () => cy.get('#someId3');

export function myFunct1() {
    // Do something
}

export function myFunct2() {
    // Do something
}

export function myFunct3() {
    // Do something
}

file-where-used.js

import {
  const1, const2, const3,
  myFunct1, myFunct2, myFunct3
}

// usage of the consts/functs below

我已经尝试过尝试将它们变成一种格式,这样我就不必单独导入每个,但我无法弄清楚......我想,也许将所有内容包装为一个类并导出它,这确实有效但仅在使用require 而不是import 时...而且我还发现导出我的const 变量有困难...

尝试

export const1 = () => cy.get('#someId1');
export const2 = () => cy.get('#someId2');
export const3 = () => cy.get('#someId3');

class myClass {
    myFunct1() {
        // Do something
    }

    myFunct2() {
        // Do something
    }

    myFunct3() {
        // Do something
    }
}
module.exports = new myClass();

【问题讨论】:

    标签: javascript node.js import export cypress


    【解决方案1】:

    您可以分几个步骤解决问题。

    自定义命令/功能

    首先,您正在创建像这样的自定义命令:

    export function() {
        // Do something
    }
    

    通过将该函数放在文件cypress/support/commands.js 中,您不必将其导入到集成文件中,但您必须重写如下:

    Cypress.Commands.add('myFunct1', function () {
        // Do something
    })
    

    你最终在集成文件中是这样的:

    cy.myFunct1()
    

    全局变量

    您正在像这样分配全局变量:

    export const1 = () => cy.get('#someId1');
    export const2 = () => cy.get('#someId2');
    export const3 = () => cy.get('#someId3');
    

    首先将它们重写为常量:

    const const1 = () => cy.get('#someId1');
    const const2 = () => cy.get('#someId2');
    const const3 = () => cy.get('#someId3');
    

    您总是需要一个一个地导入它们,但只要它们在一个文件中,您就可以将它们组合起来。您可以像这样将它们导入到测试文件中:

    import {const1, const2, const3} from '<FILE_DIRECTORY>'
    

    现在它们可以通过整个测试文件获得。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 2020-08-30
    • 2012-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多