此代码块用于读取 Excel 文件并通过给定用户角色获取用户数据。
但是如果excel文件中不存在该用户角色,则会返回一个未定义的值。
如何检查
user
变量是否未定义或为 null?
cy.task('getExcelData', Cypress.env('usersFilePath')).then((users) => {
const user = users.find(user => {
return user.userRole === 'userRole';
});
cy.wrap(user).should('not.be.empty');
cy.wrap(user).should('not.be.a',undefined)
cy.wrap(user).should('not.be.a',null)
signIn(user.username, user.password);
});
cy.wrap(user).should('not.be.empty')
(这部分有效,但其他部分无效)
这是我收到的错误:
请参阅 chaijs .a(type[, msg])
断言目标的类型等于给定的字符串类型。类型不区分大小写。
expect(undefined).to.be.an('undefined')
.a()
或.an()
正在执行typeof
检查并返回字符串,因此您只需引用"undefined"
类型
cy.wrap(user).should('not.be.a', "undefined")
或删除
.a
进行参考检查
cy.wrap(user).should('not.be', undefined)
由于如果找不到用户,测试就无法继续,所以你可以抛出一个错误。
cy.task('getExcelData', Cypress.env('usersFilePath')).then((users) => {
const user = users.find(user => user.userRole === 'userRole')
if (!user) throw new Error(`Excel data does not have user with role "${userRole}"`)
signIn(user.username, user.password)
})
空、null 和未定义的值都是 falsy,因此如果不是 true,你可能会抛出错误。
cy.task('getExcelData', Cypress.env('usersFilePath')).then((users) => {
const user = users.find(user => {
if(!user) {
throw new Error('user is empty, null, or undefined', user)
}
return user.userRole === 'userRole';
});
signIn(user.username, user.password);
});
如果要检查搜索 users 数组的结果,请在
.find()
函数之外进行。
如果未找到具有所需角色的用户,则
.find()
函数返回 undefined
(绝不为 null、空字符串或空数组)。
cy.task('getExcelData', Cypress.env('usersFilePath')).then((users) => {
/*
e.g users = [
{ userRole: 'admin', username: '...', password: '...' },
{ userRole: 'userRole', username: '...', password: '...' },
]
*/
const user = users.find(user => user.userRole === 'userRole')
if (!user) {
throw new Error('user is undefined')
}
signIn(user.username, user.password);
})