Komo
Komo

Reputation: 2138

Unit testing array using items indexes

I'm unit testing methods that are applied on an array and change its items states. Those items have different properties. For example, my array is the following :

var array = [{state: false}, {status: true}, {health: true}];

After the method is applied (items order is relevant), I'm checking that the values have changed and are the ones I expect (I'm using mocha, chai) :

expect(array[0]).to.have.property('state', true);
expect(array[1]).to.have.property('status', false);
expect(array[2]).to.have.property('health', false);

Now, say that I want to add new energy items to my array :

var array = [{state: false}, **{energy: true}**,  {status: true}, **{energy: true}**, {health: true}];

I would have to changes my 0, 1, 2 indexes of my test to 0, 2, 4, and also add new tests for my new items.

What would be a good way of using (or not using) indexes so that each time I add new items types, I don't have to change all indexes ?

Upvotes: 0

Views: 826

Answers (2)

Louis
Louis

Reputation: 151391

You could test your result against a template that is structured in the way you expect. In the following code expected is the template.

var chai = require("chai");
var expect = chai.expect;

var a = [{state: false}, {energy: true}, {status: true}, {health: true}];

var expected = [
    {state: false},
    {energy: true},
    {status: true},
    {health: true}
];

for (var i = 0, item; (item = expected[i]); ++i) {
    expect(a[i]).to.eql(expected[i]);
}

You could also do:

expect(a).to.eql(expected);

but if you do this Mocha produces an utterly uninformative assertion failure message: expected [ Array(4) ] to deeply equal [ Array(4) ]. Performing the expects one by one in a loop allows you to get better messages. Like expected { state: true } to deeply equal { state: false }.

Upvotes: 1

user1777136
user1777136

Reputation: 1756

There is a plugin chai-things for chai which makes this really readable:

[{ a: 'cat' }, { a: 'dog' }].should.contain.a.thing.with.property('a', 'cat')

Upvotes: 0

Related Questions