我想在我的测试用例中从 Cypress 中的 JSON 夹具文件读取数据。
无论出于何种原因,它都不起作用。我遵循了一些说明和示例,但根本无法使其发挥作用。我做错了什么?
这是我的文件和代码片段。
测试用例:
describe('Test for user data via JSON', ()=> {
// Use the cy.fixture() method to pull data from fixture file
before(function () {
cy.fixture('users').then(function (userData) {
this.userData = userData;
})
})
it.only('Login Test. User1', () => {
cy.wait(500)
cy.visit('http://localhost/')
cy.wait(500)
onLoginPage.usernameInput(this.userData[0].username)
onLoginPage.passwordInput(this.userData[0].password)
onLoginPage.buttonGo()
})
})
JSON 文件
文件名:users.json
[
{
"id": 0,
"username": "User1",
"password": "password1",
"_comment": "All rights"
},
{
"id": 1,
"username": "User2",
"password": "password2",
"_comment": "All rights"
},
{
"id": 2,
"username": "User3",
"password": "password3",
"_comment": "Reading only"
}
]
错误信息是: “无法读取未定义的属性(读取‘用户’)” 错误消息标记了“u”或“users”:
onLoginPage.usernameInput(this.**u**sers[0].username)
fixture文件夹在这里是分层的: “../装置/用户”
我见过的例子看起来很简单。不知道我在这里错过了什么。
非常感谢。
尝试在
then()
中使用箭头函数,就像稍后在 only()
中所做的那样。箭头函数和“常规”匿名函数之间的作用域工作方式不同,这意味着该函数内的 this
指的是不同的作用域。因此,您可能会在与稍后访问的对象不同的对象上设置 userData
属性。
注意:我假设您的错误消息指的是
this.userData
,而不是 this.users
,因为您从未在代码中实际读取过此属性。