【问题标题】:How to customize assertions in Cypress如何在 Cypress 中自定义断言
【发布时间】:2020-01-30 10:48:13
【问题描述】:

我需要测试一个对象数组是否包含某个值。测试是用 Cypress 编写的,为此,我使用 cy.wrap.some()

我的代码如下所示:

const myCustomArray = [{ name: 'Lisa' }, { name: 'Katie' }];
cy.wrap(myCustomArray.some((user) => {
    if (user.name === 'Lisa') {
      return true;
    } else {
      return false;
    }
  })).should('eq', true);

这很好用,但问题是它会在赛普拉斯控制台中返回一个非常非特定的消息。

我想要的是,以一种可以理解消息的方式更改我的代码。在这个想法中,它会是这样的:

const myCustomArray = [{ name: 'Lisa' }, { name: 'Katie' }];
cy.wrap(myCustomArray.some((user) => {
    if (user.name === 'Lisa') {
      return 'user name is Lisa';
    }
  })).should('eq', 'user name is Lisa');

但这不能工作,因为.some() 只能返回一个布尔值。我想有一个数组函数可以帮助我做到这一点,但我找不到哪个。

我不确定是否:

  • 我不知道有一些赛普拉斯命令可以解决这个问题,例如。自定义断言消息。
  • 或者它可以使用 JavaScript 来解决

两种解决方案都适合我。

【问题讨论】:

  • 与其将if 放在some 中,不如将其放在后面,使用三元组:a.some() ? 'username is lisa' : null

标签: javascript arrays cypress


【解决方案1】:

使用.find() 代替.some() 怎么样,并且对结果进行深度eq,

cy.wrap(myCustomArray.find(user => user.name === 'Lisa')) 
  .should('deep.eq', { name: 'Lisa' });

ASSERT 期望 { name: Lisa } 完全等于 { name: Lisa }

或者如果你有大的物体,只是想看看名字,

cy.wrap(myCustomArray.map(user => user.name).find(name => name === 'Lisa')) 
  .should('eq', 'Lisa');

ASSERT 期望 Lisa 等于 Lisa

【讨论】:

    猜你喜欢
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-12
    相关资源
    最近更新 更多