Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 431
Explosion Pills Avatar asked Apr 01 '15 00:04

Explosion Pills


People also ask

How do you check an array contains an element?

The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.

What is array [- 1 in JavaScript?

As others said, In Javascript array[-1] is just a reference to a property of array (like length ) that is usually undefined (because it's not evaluated to any value).

What is assertion in mocha?

Mocha is a popular JavaScript test framework that helps us structure and run our test cases. On the other hand, Mocha does not check the behaviour of our code. Assertions are the way of checking the truthness of a given piece of code and whether it properly functions as it is expected to do so.

How do you write an array In Node JS?

Creating an Array Object The first is simply by typing the array object. var array = []; Option two is to create an Array object by instantiating the Array object. var array = new Array();


2 Answers

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.

like image 66
Rodrigo Medeiros Avatar answered Sep 28 '22 04:09

Rodrigo Medeiros


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));
like image 38
Andbdrew Avatar answered Sep 28 '22 04:09

Andbdrew