【问题标题】:How to write reusable "before" in Cypress?如何在 Cypress 中编写可重用的“之前”?
【发布时间】:2021-08-14 11:52:00
【问题描述】:

我想编写可重用的“之前”部分,但未能将变量从主文件 (A.js) 传递到导入的代码 (HelloUtil.js)。提前感谢您提供的任何建议。

A.js

import * as UTIL from "./HelloUtil"

let variableFileA = "Hello"

// I hope the imported 'before' section is able to get 'variableFileA'

describe(`Do something`, () => {
    it('A "It" section', () => {
        cy.log("....")
    });
})

HelloUtil.js

before('Reusable "before" 1', () => {
    cy.log("lets begin....")
});

before('Reusable "before" 2', () => {
    cy.log("print variable:"+variableFileA)
});

我收到的结果:

【问题讨论】:

    标签: javascript cypress cypress-component-test-runner


    【解决方案1】:

    不,这是行不通的。

    如果要在其中使用变量,则需要在 HelloUtil.js 中定义 variableFileA 变量。或者您可以将变量作为参数传递。但你也没有这样做。

    可行的是:

    utils.js

    export const beforeFunc = () => {
      cy
        .log('Before func from utils.js');
    };
    

    test.js

    import { beforeFunc } from './utils';
    
    describe('My example test suite', () => {
    
      before(beforeFunc);
    });
    

    如果你想传递一些参数,你可以这样做:

    utils.js

    export const beforeFunc = (greetings) => {
      cy
        .log(greetings);
    };
    

    test.js

    import { beforeFunc } from './utils';
    
    describe('My example test suite', () => {
    
      before(() => beforeFunc('Hi'));
    });
    

    以及测试运行器的结果:

    【讨论】:

      【解决方案2】:

      我会使用可以粘贴到任何部分的custom command - 无论是之前、之后还是它等等。例如:

      import file from 'filePath'
      Cypress.Commands.add('reusableBefore2', () => {
         cy.log("print variable:" + file)
      })
      

      您可以随时通过以下方式调用它:cy.reusableBefore2()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-26
        • 2022-08-17
        • 1970-01-01
        • 2019-12-13
        • 1970-01-01
        • 1970-01-01
        • 2011-02-06
        • 2021-11-29
        相关资源
        最近更新 更多