CHAI测试:要包含对象类型的数组

人气:312 发布:2022-10-16 标签: node.js unit-testing typescript chai mocha.js

问题描述

我当前正在测试Node.js/tyescript应用程序。

我的函数应返回对象数组。

这些对象的类型应为:

type myType = {
  title: string;
  description: string;
  level: number;
  categorie: string;
  name: string;
};

以下代码不起作用

const ach: any = await achievementsServiceFunctions.getAchievementsDeblocked(idAdmin);
expect(ach)
  .to.be.an('array')
  .that.contains('myType');
如何检查我的数组是否仅包含给定类型?(未在chai文档上找到此信息)

推荐答案

Chai不提供直接测试数组中所有元素的类型的方法。因此,假设数组的所有元素都属于同一类型,我将首先测试目标是否确实是一个数组,然后迭代其内容以测试其类型,如下所示:

const expect = require('chai').expect

// create a new type 
class MyType extends Object {
  constructor() {
    super()
  }
}
// Note that this should be consistent with 
// TypeScript's 'type' directive)

// create some testable data
const ary = [
  new MyType,
  'this will FAIL',
  new MyType
]

// first, test for array type
expect(ary).to.be.an('array')

// then, iterate over the array contents and test each for type
ary.forEach((elt, index) => {
    expect(
      elt instanceof MyType, 
      `ary[${index}] is not a MyType`
    ).to.be.true
})

哪一项将输出:

/.../node_modules/chai/lib/chai/assertion.js:141
  throw new AssertionError(msg, {
  ^
AssertionError: ary[1] is not a MyType: expected false to be true
  at ary.forEach (.../testElementTypes.js:12:38)
  at Array.forEach (<anonymous>)
  at Object.<anonymous> (.../testElementTypes.js:11:5)
  at Module._compile (module.js:624:30)
  at Object.Module._extensions..js (module.js:635:10)
  at Module.load (module.js:545:32)
  at tryModuleLoad (module.js:508:12)
  at Function.Module._load (module.js:500:3)
  at Function.Module.runMain (module.js:665:10)
  at startup (bootstrap_node.js:187:16)

如果数组内容不是同类的,则需要分别测试每个元素的类型。

415