Explosion Pills
Explosion Pills

Reputation: 191729

Node mocha array should contain an element

I want to do a simple assertion of something like

knownArray.should.include('known value')

The array is correct, but I simply can't figure out the proper assertion to use to check whether the array has this value (the index doesn't matter). I also tried should.contain but both of these throw an error that Object #<Assertion> has no method 'contain' (or 'include')

How can I check that an array contains an element using should?

Upvotes: 11

Views: 17503

Answers (4)

Christopher Adams
Christopher Adams

Reputation: 1290

In case anyone else comes across this and is using chai, this is what I used based on docs for should/include

  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());
    });
  });

I'm using webdriver.io, so you can ignore part where I'm grabbing the element, just included for completeness.

Upvotes: 0

Andbdrew
Andbdrew

Reputation: 11895

Mostly from the mocha docs, you can do

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

or if you don't mind not using should, you can always do

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

Upvotes: 6

Robert Moskal
Robert Moskal

Reputation: 22553

I like chai-things a lot:

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

It let's you do things like:

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

Upvotes: 0

Rodrigo Medeiros
Rodrigo Medeiros

Reputation: 7862

Should.js has the containEql method. In your case:

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

The methods include, includes and contain you would find in chai.js.

Upvotes: 15

Related Questions