google / intermock

Mocking library to create mock objects with fake data for TypeScript interfaces
https://google.github.io/intermock/
Apache License 2.0
1.14k stars 71 forks source link

RFC: Support generating factories #54

Closed Xiphe closed 3 years ago

Xiphe commented 3 years ago

When using mock data in tests I would like to

  1. overwrite partial data (and have type-support for it out of the box)
  2. be able to create different variants of the same data-type

From this:

interface Person {
   email: string
   /** @mockType {name.firstName} */
   firstName: string
}
interface Family {
  /** @mockType {name.lastName} */
  name: string
  members: Person[]
}

To this:

import faker from 'faker';
import type * as Types from './types';

export function Person(overwrites: Partial<Types.Person> = {}): Types.Person {
  return {
    email: faker.internet.email(),
    firstName: faker.name.firstName(),
    ...overwrites
  }
}

export function Family(overwrites: Partial<Types.Family> = {}): Types.Family {
  return {
    name: faker.name.lastName(),
    members: Array.from({ length: faker.random.number(8) }).map(() => Person()),
    ...overwrites
  }
}

I guess supporting exactly this would be to specific for this library and possibly extend its scope but a intermediate step would be to support a "raw" outputFormat like this

{
  "Person": {
     "email": { "fake": "internet.email" },
     "firstName": { "fake": "name.firstName" }
  },
  "Family": {
    "firstName": { "fake": "name.lastName" },
    "members": { 
      "array": {
        "range": [1, 8],
        "contains": [{ "type": "Person" }]
      }
    }
  } 
}

which could then be used to create such factories.


What's your opinion on this? If it sounds interesting, I'd like to create a PR.

Xiphe commented 3 years ago

Closing since i'm currently making good progress combining https://github.com/vega/ts-json-schema-generator and https://github.com/json-schema-faker/json-schema-faker to build the factories.