chai testing:包含对象类型的数组

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

我目前正在测试Node.js / Typescript应用程序。

我的功能应该返回一个对象数组。

这些对象应该是类型:

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 doc上找到这个信息)

node.js unit-testing typescript mocha chai
1个回答
1
投票

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)

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

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