如何在cypress中检查变量是否为空/null/未定义

问题描述 投票:0回答:3

此代码块用于读取 Excel 文件并通过给定用户角色获取用户数据。但如果excel文件中不存在该用户角色,则会返回一个未定义的值。我们如何检查“user”变量是否未定义或为空?

 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'); (这部分有效,但其他部分无效)

这是我在 cypress 中遇到的错误

所以我想知道如何使用 cypress 命令检查该值是否为空或未定义

javascript cypress chai
3个回答
3
投票

请参阅 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)
})

2
投票

空、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);
        });

2
投票

如果要检查搜索 users 数组的结果,请在

.find()
函数之外进行。

如果未找到具有所需角色的用户,则

.find()
函数返回
undefined
(绝不为 null、空字符串或空数组)。

参考 Array.prototype.find()

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);
})
© www.soinside.com 2019 - 2024. All rights reserved.