首页 > 解决方案 > 如何在 Cypress 中编写可重用的“之前”?

问题描述

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

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)
});

我收到的结果:

在此处输入图像描述

标签: javascriptcypresscypress-component-test-runner

解决方案


不,这是行不通的。

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

可以工作的是:

实用程序.js

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

测试.js

import { beforeFunc } from './utils';

describe('My example test suite', () => {

  before(beforeFunc);
});

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

实用程序.js

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

测试.js

import { beforeFunc } from './utils';

describe('My example test suite', () => {

  before(() => beforeFunc('Hi'));
});

以及来自测试运行器的结果:

在此处输入图像描述


推荐阅读