使用项目索引的单元测试数组

Unit testing array using items indexes

本文关键字:单元测试 数组 索引 项目      更新时间:2023-09-26

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

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会产生一个完全没有信息的断言失败消息:expected [ Array(4) ] to deeply equal [ Array(4) ]。在循环中一个接一个地执行期望,可以获得更好的消息。如expected { state: true } to deeply equal { state: false }

有一个用于chai的插件chai-things,它使这些内容真正具有可读性:

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