You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Cypress中检查user变量不为undefined或null?

如何正确检查Cypress中user变量不为undefined或null?

问题场景

通过Cypress读取Excel文件并根据指定角色筛选用户数据,当目标角色不存在时user会返回undefined。需要校验user既不是undefined也不是null,现有代码中cy.wrap(user).should('not.be.empty')可正常运行,但检查undefined和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);
});

报错截图

报错截图

正确的校验方式

方式1:使用exist断言

Cypress的exist断言可直接判断变量是否为null或undefined,写法简洁高效:

cy.wrap(user).should('exist');

方式2:使用oneOf精准排除

若需要明确指定排除null和undefined,可以用oneOf断言实现:

cy.wrap(user).should('not.be.oneOf', [null, undefined]);

方式3:同步提前判断

如果不想等到断言阶段才触发错误,也可以在同步代码里提前校验,避免后续signIn执行时因user为空抛出错误:

cy.task('getExcelData', Cypress.env('usersFilePath')).then((users) => {
  const user = users.find(user => user.userRole === 'userRole');

  if (!user) {
    throw new Error(`未找到角色为userRole的用户数据`);
  }
  
  signIn(user.username, user.password);
});

报错原因说明

原代码中should('not.be.a', undefined)报错,是因为not.be.a断言的第二个参数需要是字符串类型的类型名称(比如'undefined'),但即使修改为字符串,not.be.a对null的判断也不准确(null的类型是'object'),因此不推荐这种写法。

内容的提问来源于stack exchange,提问作者yasith rangana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 06:20:23