赛普拉斯如何将全局常量存储在可以在所有规范文件中使用的文件中?

时间:2018-04-06 20:20:41

标签: variables testing global cypress

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

6 个答案:

答案 0 :(得分:2)

以下链接可以帮助您轻松设置和获取env变量。 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')
  })
})

答案 1 :(得分:1)

使用项目根目录中的cypress.json文件。

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

设置了一些env变量后,您可以按照以下规范引用它们:Cypress.env('your_var');

答案 2 :(得分: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?'

答案 3 :(得分:0)

全局变量 - 听起来像灯具。

请参阅writefile - JSON - Write response data to a fixture file

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

小心分享你为什么要这样做?
听起来很有趣。

答案 4 :(得分:0)

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

cypress.json

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

cypress.env.json

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

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

const myVar = Cypress.env('myVar')

您可以在赛普拉斯赛跑者的“设置”选项卡中查看环境变量。

cypress runner Settings

答案 5 :(得分:0)

我喜欢创建一个常量文件,比如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');
});
相关问题