11

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?

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405

4 Answers4

15

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.

Rodrigo Medeiros
  • 7,814
  • 4
  • 43
  • 54
  • hi @rodrigo, how to equal two arrays in should? – Koustuv Sinha Apr 24 '15 at 05:35
  • 1
    @KoustuvSinha, it depends on what do you consider an equality between two arrays. Are they the same if all the elements are equal, but in a different order? Or does the order matter? This problem may be depper than you have considered. Take a look at [this queestion here](http://stackoverflow.com/questions/7837456/comparing-two-arrays-in-javascript) or even in libraries like [LoDash](https://lodash.com/), which provides a lot of useful features, like the [isEqual](https://lodash.com/docs#isEqual) method. If that does not answer your question, ask a new question in SO, I'll be glad to discusss. – Rodrigo Medeiros Apr 24 '15 at 11:23
6

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));
Andbdrew
  • 11,788
  • 4
  • 33
  • 37
0

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');
Robert Moskal
  • 21,737
  • 8
  • 62
  • 86
0

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.

Christopher Adams
  • 1,240
  • 10
  • 14