8

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
  • You cannot create values from types. TypeScript type information does not exist at run time. Commented Aug 15, 2020 at 12:10
  • 1
    I think this should be possible using code-generation. Where you'd create the factories with a cli, not at runtime. I'm currently looking for such a thing, might build it. Commented Apr 14, 2021 at 8:59

2 Answers 2

3

When you create the factories with a cli, not at runtime it's possible:

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.