【问题标题】:Node mocha array should contain an element节点 mocha 数组应该包含一个元素
【发布时间】:2015-06-05 12:12:40
【问题描述】:

我想做一个简单的断言,比如

knownArray.should.include('known value')

数组是正确的,但我根本无法找出正确的断言来检查数组是否有这个值(索引无关紧要)。我也尝试过should.contain,但这两个都抛出了Object #<Assertion> has no method 'contain'(或'include')的错误

如何使用should 检查数组是否包含元素?

【问题讨论】:

    标签: arrays node.js mocha.js should.js


    【解决方案1】:

    Mostly from the mocha docs,你可以做

    var assert = require('assert');
    var should = require('should');
    
    describe('Array', function(){
      describe('#indexOf(thing)', function(){
        it('should not be -1 when thing is present', function(){
          [1,2,3].indexOf(3).should.not.equal(-1);
        });
      });
    });
    

    或者如果你不介意不使用 should,你可以随时使用

    assert.notEqual(-1, knownArray.indexOf(thing));
    

    【讨论】:

      【解决方案2】:

      Should.js 具有 containEql 方法。在你的情况下:

      knownArray.should.containEql('known value');
      

      includeincludescontain 方法可以在 chai.js 中找到。

      【讨论】:

      • 嗨@rodrigo,如何让两个数组相等?
      • @KoustuvSinha,这取决于您认为两个数组之间的相等性。如果所有元素都相等但顺序不同,它们是否相同?还是顺序重要?这个问题可能比你想象的要严重。看看this queestion here 甚至是像LoDash 这样的库,它提供了很多有用的特性,比如isEqual 方法。如果这不能回答您的问题,请在 SO 中提出一个新问题,我很乐意讨论。
      【解决方案3】:

      我非常喜欢柴东西:

      https://github.com/RubenVerborgh/Chai-Things

      它可以让你做这样的事情:

      [{ a: 'cat' }, { a: 'dog' }].should.include({ a: 'cat' });
      ['cat', 'dog'].should.include('cat');
      

      【讨论】:

        【解决方案4】:

        如果其他人遇到这个并且正在使用 chai,这就是我根据文档使用的应该/包含

          it(`Should grab all li elements using double $$`, () => {
            const liEl = $$('ul li');
        
            const fruitList = ['Bananas', 'Apples', 'Oranges', 'Pears'];
        
            liEl.forEach((el) => {
              expect(fruitList).to.include(el.getText());
            });
          });
        

        我正在使用 webdriver.io,因此您可以忽略我抓取元素的部分,只是为了完整性而包含在内。

        【讨论】:

          猜你喜欢
          • 2017-09-20
          • 2019-03-22
          • 1970-01-01
          • 2021-03-05
          • 2014-05-02
          • 1970-01-01
          • 2016-12-27
          • 2017-12-13
          • 1970-01-01
          相关资源
          最近更新 更多