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

chai testing: array to include type of objects

我目前正在测试一个节点。js/Typescript 应用程序。

我的函数应该return一个对象数组。

这些对象的类型应该是:

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 上找到此信息)

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)

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

您也可以使用 chai-json-pattern 插件。

Chai JSON pattern allows you to create blueprints for JavaScript objects to ensure validation of key information. It enables you to use JSON syntax extends with easy to use validators.

此外,由于chai-json-pattern插件目前不支持TypeScript,我们需要扩展chai.Assertion的方法类型。

我使用faker包生成符合myType的随机测试数据。

例如

import faker from 'faker';
import chai, { expect } from 'chai';
import chaiJsonPattern from 'chai-json-pattern';
chai.use(chaiJsonPattern);

declare global {
  export namespace Chai {
    interface Assertion {
      matchPattern(pattern: string): void;
    }
  }
}

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

describe('49047322', () => {
  it('should pass if the data has correct types', () => {
    const ach: myType[] = [
      {
        title: faker.name.title(),
        description: faker.lorem.sentence(),
        level: faker.random.number(),
        categorie: faker.lorem.word(),
        name: faker.name.findName(),
      },
      {
        title: faker.name.title(),
        description: faker.lorem.sentence(),
        level: faker.random.number(),
        categorie: faker.lorem.word(),
        name: faker.name.findName(),
      },
    ];
    expect(ach).to.matchPattern(`
      [
       {
        "title": String,
        "description":String,
        "level": Number,
        "categorie": String,
        "name": String
       }
      ]
    `);
  });

  it('should fail if the data has incorrect types', () => {
    const ach: myType[] = [
      {
        title: 1 as any,  // Simulate wrong type of data
        description: faker.lorem.sentence(),
        level: faker.random.number(),
        categorie: faker.lorem.word(),
        name: faker.name.findName(),
      },
    ];
    expect(ach).to.matchPattern(`
      [
       {
        "title": String,
        "description":String,
        "level": Number,
        "categorie": String,
        "name": String
       }
      ]
    `);
  });
});

测试结果:

  49047322
    ✓ should pass if the data has correct types
    1) should fail if the data has incorrect types


  1 passing (27ms)
  1 failing

  1) 49047322
       should fail if the data has incorrect types:

      AssertionError: expected [ Array(1) ] to be like [ Array(1) ]
      + expected - actual

           "categorie": "nisi"
           "description": "Quae aut sint et earum quae."
           "level": 69341
           "name": "Mozell Green MD"
      -    "title": 1
      +    "title": "String"
         }
       ]
      
      at Context.it (src/Whosebug/49047322/main.test.ts:63:20)