14

我正在寻找一种将全局常量存储在一个文件中的方法,该文件可以在我的所有规范文件中使用。任何人都可以帮忙吗?

4

6 回答 6

16

像这样使用cypress.json项目根目录中的文件:

{
    "env": {
        "your_var": "your_value"
    }
}

https://docs.cypress.io/guides/references/configuration.html

一旦你设置了一些环境变量,你可以像这样从你的规范中引用它们:Cypress.env('your_var');

于 2018-04-09T16:57:14.173 回答
4

以下链接可能有助于设置和获取环境变量的简单方法。 https://docs.cypress.io/api/cypress-api/env.html#Syntax

describe('My First Test', function() {
  it('it set value to global variable', function() {
    Cypress.env('some_variable', "hello")
  })
  it('it get value to global variable', function() {
    expect(Cypress.env('some_variable')).to.equal('hello')
  })
})
于 2018-11-16T13:08:21.663 回答
2

全局变量 - 听起来像固定装置。

请参阅writefile - JSON - 将响应数据写入夹具文件

cy.request('https://jsonplaceholder.typicode.com/users').then((response) => {
  cy.writeFile('cypress/fixtures/users.json', response.body)
})

// our fixture file is now generated and can be used
cy.fixture('users').then((users) => {
  expect(users[0].name).to.exist
})

愿意分享您为什么要这样做吗?
听起来可能很有趣。

于 2018-04-07T03:25:04.647 回答
1

我喜欢创建一个常量文件,例如 constants.js 作为可导出的常量对象:

export const NAME = {
FIRST: 'John',
LAST: 'Smith',
};

并在我的规范文件中导入它们:test.spec.js

import { NAME } from '../../support/constants';

describe('Landing page', () => {
  beforeEach(() => cy.login());

  cy.get(NAME.FIRST).assertion('verify the name');
});
于 2021-01-07T16:44:57.627 回答
1

您可以使用存储在cypress.jsoncypress.env.json中的环境变量。

柏树.json

{
  "env": {
    "myVar": "value..."
  }
}

cypress.env.json

{
  "myVar": "value..."
}

您可以使用Cypress.env('myVar')来使用环境变量。

const myVar = Cypress.env('myVar')

您可以在 cypress runner 的设置选项卡中查看您的环境变量。

赛普拉斯赛跑者设置

于 2019-11-03T22:32:18.920 回答
1

由于 cypress 是 js,因此可以在 js 文件 (my-const.js) 上定义 const 为

export const ARE_YOU_SURE='Are you sure';

并在另一个文件中使用它们

import * as constants from "../[proper path]/my-conste.js";
...
var s = constants.ARE_YOU_SURE + ' about this?'
于 2020-11-13T17:21:59.323 回答