测试对象是否符合TypeScript中的接口

时间:2015-06-15 23:48:36

标签: testing typescript

如果我有一个普通的JavaScript对象和一个TypeScript接口,我怎样才能编写一个断言符合我界面的对象的测试?

interface Person {
  name: string
  age?: number
}

describe('Person interface check', () => {
  it ('should conform to "Person" interface', () => {
     let obj1 = {name: "Mohsen"};
     let obj2 = {name: "Hommer", age: 40};

     expect(obj1) // ????
  });
});

编辑:我不想做深度断言,例如expect(obj1.name).to.be.a.string

3 个答案:

答案 0 :(得分:5)

  

断言符合我界面的对象

你必须手动完成:

expect(typeof object.name).to.eql("string");
// so on 

更新:编写代码为您做深度断言

由于生成的JS中的 TypeScript 类型信息已删除,因此您无法访问js 中的类型信息 。但是,您可以编写代码来获取代码的TS视图(使用typescript语言服务)并生成为您执行这些深层断言的JS代码。

答案 1 :(得分:1)

我刚刚遇到了同样的问题,我的解决方案是构建我的界面的 json schema
您可以使用 automated tool 为您构建它,方法是传递您的自定义界面,如下所示:

typescript-json-schema "./myfile.ts" MyCustomType --strictNullChecks --noExtraProps --required --out=output.json

然后,您可以使用扩展 jest-json-schema 来检查您的对象是否与您生成的架构匹配,如下所示:

const mySchema = require('path/to/output.json')
expect(myStrangeObject).toMatchSchema(mySchema)

这对我来说就像一个魅力。

(我建议熟悉 json 模式关键字,因为这些标志“--strictNullChecks --noExtraProps --required”在根据您的接口定义生成模式时会产生很大的不同)

答案 2 :(得分:0)

有许多不同的软件包,可让您在“类型检查”时对此进行测试。

以下是我写的一个示例:https://tsplay.dev/oN94ow