【问题标题】:Cypress: using either or with expect赛普拉斯:使用或与期望
【发布时间】:2021-05-19 22:29:58
【问题描述】:

我正在使用 cypress 并且有一个具有一些属性的对象,例如:

const obj={
  a:1,
  b:2,
  c:3
}

我想在那里检查这个对象:

  1. 两者都不应该有属性myProp
  2. 或者应该将属性myProp 作为一个空字符串
  3. 或者应该有一个属性myProp未定义

我首先尝试了前两个条件,但本身就失败了,因此无法满足所有 3 个条件。

这是我尝试过的:

expect(obj)
        .either.not.to.have.a.property('myProp')
        .or.to.have.a.property('myProp')
        .that.is.a('string').and.is.empty;

我看到错误如下:

请帮帮我:

  1. 使用/或
  2. 检查所有 3 个条件。

【问题讨论】:

    标签: javascript unit-testing testing cypress chai


    【解决方案1】:

    您可以使用自定义匹配器,这是一个具有任意复杂度并返回 true 或 false 的函数。

    function checkMyProp(obj) {
      const myProp = obj['myProp'];
      return myProp === undefined ||
        (myProp !== undefined && typeof myProp === 'string' && myProp === '');
    }
    
    it('succeeds when myProp does not exist', () => {
      const obj={ a:1, b:2, c:3 }
      expect(obj).to.satisfy(checkMyProp, 'myProp meets the criteria');
    })
    
    it('succeeds when myProp is an empty string', () => {
      const obj={ a:1, b:2, c:3, myProp: '' }
      expect(obj).to.satisfy(checkMyProp, 'myProp meets the criteria');
    })
    
    it('fails when myProp is a string but not empty', () => {
      const obj={ a:1, b:2, c:3, myProp: 'myValue' }
      expect(obj).to.satisfy(checkMyProp, 'myProp meets the criteria');
    })
    
    it('fails when myProp is a number', () => {
      const obj={ a:1, b:2, c:3, myProp: 4 }
      expect(obj).to.satisfy(checkMyProp, 'myProp meets the criteria');
    })
    

    如果要在测试中配置匹配器,使用高阶函数(返回函数的函数)

    function matcherFor(prop) {
      return (obj) => {
        const myProp = obj[prop];
        return myProp === undefined ||
          (myProp !== undefined && typeof myProp === 'string' && myProp === '');
      }
    }
    
    it('succeeds when myProp does not exist', () => {
      const obj={ a:1, b:2, c:3 }
      expect(obj).to.satisfy(matcherFor('myProp'), 'myProp meets the criteria');
    })
    

    或作为单线(=== 运算符中隐含 typeof 检查)

    const matcherFor = (prop) => (obj) => obj[prop] === undefined || obj[prop] === '';
    

    您可以使用与 .should() 相同的语法作为命令中的验证步骤

    it('as a validation step in a test chain', () => {
      const obj={ a:1, b:2, c:3 }
      cy.wrap(obj)
        .should('satisfy', matcherFor('myProp'), 'myProp meets the criteria')
        .then(obj => {
          // process object
        })
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-28
      • 1970-01-01
      • 2019-08-20
      • 2020-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多