Cypress 简明教程

Cypress - Data Driven Testing

Cypress 数据驱动测试借助 fixtures 得以实现。Cypress fixtures 被添加到维护和保存自动化测试数据中。

Cypress data driven testing is achieved with the help of fixtures. Cypress fixtures are added to maintain and hold the test data for automation.

fixtures 保存在 Cypress 项目中的 fixtures 文件夹(example.json 文件)中。它基本上帮助我们从外部文件获取数据输入。

The fixtures are kept inside the fixtures folder (example.json file) in the Cypress project.Basically, it helps us to get data input from external files.

fixtures

Cypress fixtures 文件夹可以有 JavaScript 对象表示法 (JSON) 或其他格式的文件,并且数据以“键: 值”对进行维护。

Cypress fixtures folder can have files in JavaScript Object Notation (JSON) or other formats and the data is maintained in "key:value" pairs.

所有测试数据都可以被多个测试使用。所有固定数据都必须在 before 钩子块内声明。

All the test data can be utilised by more than one test. All fixture data has to be declared within the before hook block.

Syntax

Cypress 数据驱动的测试语法如下所示:

The syntax for Cypress data driven testing is as follows −

cy.fixture(path of test data)
cy.fixture(path of test data, encoding type)
cy.fixture(path of test data, opts)
cy.fixture(path of test data, encoding type, options)

在此,

Here,

  1. path of test data is the path of test data file within fixtures folder.

  2. encoding type − Encoding type (utf-8, asci, and so on) is used to read the file.

  3. Opts − Modifies the timeout for response. The default value is 30000ms. The wait time for cy.fixture(), prior throws an exception.

Implementation in example.json

下面给出在 Cypress 中使用 example.json 进行数据驱动测试的实现:

Given below is the implementation of data driven testing with example.json in Cypress −

{
   "email": "abctest@gmail.com",
   "password": "Test@123"
}

Implementation of Actual Test

在 Cypress 中实际进行数据驱动测试的实现如下:

The implementation of actual data driven testing in Cypress is as follows −

describe('Tutorialspoint Test', function () {
   //part of before hook
   before(function(){
      //access fixture data
      cy.fixture('example').then(function(signInData){
         this.signInData = signInData
      })
   })
   // test case
   it('Test Case1', function (){
      // launch URL
      cy.visit("https://www.linkedin.com/")
      //data driven from fixture
      cy.get('#session_key ')
      .type(this.signInData.email)
      cy.get('# session_password').type(this.signInData.password)
   });
});

Execution Results

Execution Results

输出如下:

The output is as follows

implementation of actual test

输出日志显示值 abctest@gmail.com 和 Test@123 分别输入到“电子邮件”和“密码”字段。这些数据已从固定数据传递到测试。

The output logs show the values abctest@gmail.com and Test@123 being fed to the Email and Password fields respectively. These data have been passed to the test from the fixtures.