【问题标题】:chai testing: array to include type of objectschai 测试:包含对象类型的数组
【发布时间】:2018-08-09 09:09:10
【问题描述】:

我目前正在测试一个 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.js chai


    【解决方案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)
    

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

    【讨论】:

    • 太棒了!谢谢你:)
    【解决方案2】:

    您也可以使用chai-json-pattern 插件来做到这一点。

    Chai JSON 模式允许您为 JavaScript 对象创建蓝图,以确保验证关键信息。它使您能够使用带有易于使用的验证器的 JSON 语法扩展。

    另外,由于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/stackoverflow/49047322/main.test.ts:63:20)
    

    【讨论】:

      猜你喜欢
      • 2017-11-19
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 2021-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多