使用项目索引

时间:2015-06-04 09:02:10

标签: javascript unit-testing mocha chai

我是应用于数组并更改其项状态的单元测试方法。这些物品有不同的属性。 例如,我的数组如下:

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

在应用该方法之后(项目顺序是相关的),我正在检查值是否已经改变并且是我期望的那些(我正在使用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);

现在,假设我想在我的阵列中添加新的能量​​项目:

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

我必须将我的测试的0,1,2索引更改为0,2,4,并为我的新项目添加新测试。

使用(或不使用)索引的好方法是什么,每次添加新项目类型时,我都不必更改所有索引?

2 个答案:

答案 0 :(得分:1)

您可以针对以您期望的方式构建的模板测试结果。在以下代码中,expected是模板。

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

你也可以这样做:

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

但是如果你这样做,Mocha会产生一个完全没有信息的断言失败消息:expected [ Array(4) ] to deeply equal [ Array(4) ]。在循环中逐个执行期望可以让您获得更好的消息。与expected { state: true } to deeply equal { state: false }一样。

答案 1 :(得分:0)

chai有一个插件chai-things,这使得它真的可读:

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