Cypress fixtures - 无法读取未定义的属性(读取 'data')

Cypress fixtures - Cannot read properties of undefined (reading 'data')

我正在尝试使用装置来保存不同测试的数据,特别是用户凭据。这是代码示例。当进行第二次测试时,我得到 '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')
    })

这是我的 credentials.json 文件:

{
  "admin": {
    "username": "*****",
    "password": "*****"
  }
}

根据 cypress docs:

If you store and access the fixture data using this test context object, make sure to use function () { ... } callbacks. Otherwise, the test engine will NOT have this pointing at the test context.

所以,你的 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')
})

我更喜欢使用闭包变量来分配夹具数据。

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

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

Gleb Bahmutov also recommends using closure variables.

I strongly recommend using closure variables instead of this properties. The closure variables are clearly visible and do not depend on function vs () => {} syntax.

以上回答正确。执行上述操作的另一种方法是使用 cypress.json 而不是其他 json 文件。

在您的 cypress.json 中,您可以添加凭据:

{
  "Env": {
    "username": "*****",
    "password": "*****"
  }
}

并在您的 it 函数中引用 json 目录。

it('Login correct', function () {
  cy.visit('/')
  loginPage.signIn(Cypress.env('username'), Cypress.env('password'))
  cy.wait(5000)
  // assertion
  cy.contains('Dashboard').should('be.visible')
})