Cypress 装置 - 无法读取未定义的属性(读取“数据”)

Mar*_*cía 6 fixtures cypress

我正在尝试使用固定装置来保存不同测试的数据,特别是用户凭据。这是代码的示例。当进行第二次测试时,我得到了'Cannot read properties of undefined (reading 'data')'

有什么想法以及如何解决这个问题吗?这是错误的吗?

before(function () {
    cy.fixture('credentials').then(function (data) {
        this.data = data;
    })
})

    it('Login correct', () => {
        cy.visit('/')
        loginPage.signIn(this.data.admin.username,this.data.admin.password)
        cy.wait(5000)
        // assertion
        cy.contains('Dashboard').should('be.visible')
    })
Run Code Online (Sandbox Code Playgroud)

这是我的credentials.json文件:

{
  "admin": {
    "username": "*****",
    "password": "*****"
  }
}
Run Code Online (Sandbox Code Playgroud)

ago*_*off 9

尝试使用闭包变量来分配夹具数据。

describe('Some Test', () => {
  let data; //closure variable
  before(() => {
    cy.fixture('credentials').then((fData) => {
        data = fData;
    });
  });

    it('Login correct', () => {
        cy.visit('/')
        loginPage.signIn(data.admin.username, data.admin.password) //usage of closure variable to get the values from the fixtures
        cy.wait(5000)
        // assertion
        cy.contains('Dashboard').should('be.visible')
    });
});
Run Code Online (Sandbox Code Playgroud)

Gleb Bahmutov 还建议使用闭包变量。

我强烈建议使用闭包变量而不是这个属性。闭包变量清晰可见,不依赖于functionvs() => {}语法。


Ala*_*Das 6

根据cypress 文档

如果您使用此测试上下文对象存储和访问夹具数据,请确保使用 function () { ... } 回调。否则,测试引擎不会将 this 指向测试上下文。

因此,您的it块还应该使用函数:

before(function () {
  cy.fixture('credentials').then(function (data) {
    this.data = data
  })
})

it('Login correct', function () {
  cy.visit('/')
  loginPage.signIn(this.data.admin.username, this.data.admin.password)
  cy.wait(5000)
  // assertion
  cy.contains('Dashboard').should('be.visible')
})
Run Code Online (Sandbox Code Playgroud)