首页 > 解决方案 > 赛普拉斯夹具 - 类型错误:无法读取未定义的属性“travelData”

问题描述

出现错误Cypress test execution with fixture - "TypeError: Cannot read property 'travelData' of undefined"

以下是步骤:

1 - 创建一个travelData.json文件并将其放入fixtures文件夹中:

{
  "FIRSTNAME": "TESTTRAVEL",
  "LASTNAME": "USER",
  "MOBILE": "581234567",
  "EMAIL": "test@test.com",
  "PASSPORT": "AB1234",
  "CURRENCY": "AED"
}

2 - 编写赛普拉斯测试并放入integration文件夹中。代码如下:

context('Travel Portal Regression Test', () => {
  beforeEach(function () {
    cy.fixture('travel.testData').then((travelData) => {
      this.travelData = travelData;
    });
  });
  beforeEach(() => {
    // cy.viewport('iphone-6')
    cy.viewport(360, 640);
    cy.visit('https://thoughtcoders.com/');
  });

  it('Testing ThoughtCoders Homepage', () => {
    cy.log('Testing ThoughtCoders Homepage');
    cy.log(this.travelData.FIRSTNAME);
  });
});

当我运行 Cypress 测试时,我收到错误"TypeError: Cannot read property 'travelData' of undefined"

请纠正我。

标签: javascriptjsoncypress

解决方案


看看Fixture Example Recipe,它展示了一种简单的方法,可以只加载一次fixture,并为规范中的每个测试保留它

beforeEach()该模式是在 yourbefore()和 current之间添加一个额外的beforeEach()

示例配方

context('loading once and using @', () => {
  let city
  let country

  before(() => {
    // load fixtures just once, need to store in
    // closure variables because Mocha context is cleared
    // before each test
    cy.fixture('city').then((c) => {
      city = c
    })

    cy.fixture('country').then((c) => {
      country = c
    })
  })

  beforeEach(() => {
    // we can put data back into the empty Mocha context before each test
    // by the time this callback executes, "before" hook has finished
    cy.wrap(city).as('city')
    cy.wrap(country).as('country')
  })

  it('has loaded fixtures', function () {
    // again, the test has to use "function" callback
    // to make sure "this" points at the Mocha context
    expect(this.city).to.deep.equal({ name: 'Atlanta' })
    expect(this.country).to.deep.equal({ name: 'United States' })
  })
})

您需要的三个关键点是

  1. 使用闭包变量
  2. 使用 beforeEach() 在清除后“放回”变量
  3. 使用“function(){}”样式测试

在你的测试中

context('loading once and persisting the fixture', () => {

  let travelData                                                 // key point #1

  before(() => {
    cy.fixture('travelData').then((data) => {                  
      travelData = data;
    });
  })

  beforeEach(() => {                                             // key point #2
    cy.wrap(travelData).as('travelData')
  })

  beforeEach(() => {
    cy.viewport(360, 640);
    cy.visit('https://thoughtcoders.com/');
  });

  it('Testing ThoughtCoders Homepage', function () {             // key point #3 
    expect(this.travelData."FIRSTNAME").to.equal("TESTTRAVEL")   // passes
  })
})

推荐阅读