简体   繁体   English

如何从 Typescript 中的数据类型创建假 object 以进行测试

[英]How to create fake object from a data type in Typescript for testing

I'm looking for a way to simplify making fake data for unit testing in Angular solution.我正在寻找一种方法来简化在 Angular 解决方案中为单元测试制作假数据。 I am using interfaces like:我正在使用如下接口:

export interface ReferenceDataItemCommon {
  codeDescription?: string;
  code: string;
  deleted?: boolean;
}

As data types in application.作为应用程序中的数据类型。 Currently using Factory.ts + Faker to create fake objects for purpose of tests:目前使用 Factory.ts + Faker 为测试目的创建假对象:

  export const fakeReferenceDataItemCommon = Factory.Sync.makeFactory<ReferenceDataItemCommon>({
    code: Factory.each(() => Faker.lorem.word()),
    codeDescription: Factory.each(() => Faker.lorem.sentence(4)),
  });

But I'm curious if there is a way to simplify it even more for when you just want a object for your test and speed up creating it even more.但是我很好奇是否有一种方法可以进一步简化它,因为您只需要一个 object 来进行测试并更快地创建它。 Is it possible in Typescript to have a generic method that would return a object of that datatype? Typescript 中是否有可能有一个通用方法返回该数据类型的 object?

  const fake = createFake<ReferenceDataItemCommon>();

What my initial idea was is to do something like:我最初的想法是做类似的事情:

Object.keys(object).forEach(key => {
  switch(typeof object[key]) {
    case 'string':
       object[key] = Faker.lorem.word();
       break;
  }
}
return object;

And for complex object call this method recursively.对于复杂的 object 递归调用此方法。 Is that possible, and if what would be a better approach to do this as I feel a bit out of my depth?这有可能吗,如果我觉得有点超出我的深度,那么有什么更好的方法来做到这一点?

When you create the factories with a cli, not at runtime it's possible:当您使用 cli 创建工厂时,而不是在运行时,它是可能的:

https://www.npmjs.com/package/intermock looks promising https://www.npmjs.com/package/intermock看起来很有希望

I was searching for something similar too but also didn't find it.我也在寻找类似的东西,但也没有找到。 So, I create this lib https://www.npmjs.com/package/class-validator-mocker , which works with classes annotated with class-validator decorators.因此,我创建了这个库https://www.npmjs.com/package/class-validator-mocker ,它适用于使用类验证器装饰器注释的类。 If you can work with data classes instead of interfaces to define certain types, I think it's worth taking a look at it.如果您可以使用数据类而不是接口来定义某些类型,我认为值得一看。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM