我正在对应用于数组并更改其项目状态的方法进行单元测试。这些元素具有不同的属性。 例如,我的数组如下:
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,并为我的新项目添加新测试。
使用(或不使用)索引的好方法是什么,以便每次添加新项目类型时,我不必更改所有索引?
最佳答案
您可以根据按照您期望的方式构建的模板来测试您的结果。在下面的代码中,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 会生成一条完全无信息的断言失败消息:预期 [ Array(4) ] 深度等于 [ Array(4) ]
。在循环中一项一项地执行期望可以让您获得更好的消息。就像预期的 { state: true } 深度等于 { state: false }
。
关于javascript - 使用项目索引对数组进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30639492/