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

Viewed 4122

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?

2 Answers
Related