2015-06-04 37 views
0

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

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

后(项目顺序是相关的),我检查这些值已经改变,并且我希望那些(我使用的是摩卡柴):

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,也加上我的新项目的新测试。

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

回答

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

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

+1

如果使用chai.config.showDiff = true配置chai;和chai.config.truncateThreshold = 0;那么深度平等失败信息将至少包括完整的对象。不幸的是,它并没有告诉你它们在哪里不同。 –

+0

我曾尝试开启'showDiff',但没有意识到'truncateThreshold'是一个问题。这很好。谢谢!尽管如此,我仍然不愿意看到差异。 – Louis

0

有是哉插件chai-things这使得这个真正可读:

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

在我的情况下,我可以在我的数组中有多次具有相同属性的项目,并且它们在数组中的位置也很重要,因此此测试是不够的。 – Komo