How do I test array element types using BDD Javascript?

412 views Asked by At

I am writing a Javascript unit test using the BDD style. I want to test that a value

  1. is an array
  2. has all string elements

I can get the first condition with

value.should.be.an('array');

Is there a way to test for the second condition using this idiom?

2

There are 2 answers

0
Ethan Gardner On BEST ANSWER

I think a clean way to do it would be to use Array.prototype.every, which would give you a boolean value indicating if every value in the array was a string. You can then use this value in your assertion.

value.every(function(el){ 
    return typeof(el) === 'string';
}).should.be.true;
1
Chad On

What about…

var nonStrings = myArray.filter(function( val ){ return val.be.a.String; });

nonStrings.should.be.empty;