简体   繁体   中英

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. 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:

  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. Is it possible in Typescript to have a generic method that would return a object of that datatype?

  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. 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:

https://www.npmjs.com/package/intermock looks promising

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. If you can work with data classes instead of interfaces to define certain types, I think it's worth taking a look at it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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