如何使用Chai声明对象数组中的类型?

问题描述 投票:0回答:1

我具有以下上下文:

const data = [
  { 
    id: 1,
    name: 'thenamefoo',
    modified: new Date() // random date
  },
  {
    id: 2,
    name: 'namebar',
    modified: new Date() // random date
  },
  ...
];

expect(data)...

我想断言我的数据将始终是具有固定键(和类型)的对象的数组。

例如,我想要类似的东西

expect(data)
.to.be.an('array')
.that.all.have.types.like({
  id: Number,
  name: String,
  modified: Date
});

有可能吗?怎么样?有库吗?

javascript unit-testing chai assert
1个回答
0
投票

我认为,您应该集中精力验证数据,而不要使用笨拙的断言DSL。通过简单的正确/错误检查,您只需要谦虚的assert

test('my data is valid', () => {
  data.forEach(({id, name, modified}) => {
    assert(typeof id === 'number', `${id} is not a number`);
    assert(typeof name === 'string', `${name} is not a string`);
    assert(modified instanceof Date, `${modified} is not a date`);
  });
});

进一步]

如果您需要检查其他内容,这当然无济于事:

  1. 数组不为空
  2. 每个对象的属性都准确地具有idnamemodified。越来越少,没有更多
  3. [id是一个正整数
  4. name不是空字符串
  5. ...
  6. 对于更细粒度的控制,您绝对应该查看

© www.soinside.com 2019 - 2024. All rights reserved.