pronounced like
ˈfakt(ə)rē tē
TypeScript library for building data objects.
Useful for unit tests and mocking data during development
With strong typing in mind
- Provide factory for building data objects based on predefined config
- Factory instance should strongly depends from target TypeScript interface, so if interface will changed factory should not be built until syncing with interface changes
- All kind of API "sugar" appreciated but with typings in mind
npm install factory-t
To start you need
- Design your data type
interface UserDto {
id: number;
email: string;
phone: string | null;
profile: {
avatarUrl: string;
language: 'EN' | 'RU';
statusString?: string;
};
}
- Import right tools
import { factoryT, fields } from 'factory-t';
- create factory (or bunch of factories)
const profileFactory = factoryT<UserDto['profile']>({
avatarUrl: 'my.site/avatar',
language: fields.sequence(['EN', 'RU']),
statusString: fields.optional('sleeping'),
});
const userFactory = factoryT<UserDto>({
id: fields.index(),
email: (ctx) => `user-${ctx.index}@g.com`,
phone: fields.nullable('+127788'),
profile: (ctx) => profileFactory.item({ avatarUrl: `/avatars/${ctx.index}` }),
});
- and use it to build objects
expect(userFactory.item({ phone: null })).toStrictEqual({
id: 1,
email: 'user-1@g.com',
phone: null, // override by passed partial to item(...)
profile: {
avatarUrl: '/avatars/1', // override by userFactory using its index
language: 'EN',
statusString: 'sleeping',
},
});
See tutorial or/and unit test for details
I use this library in all current projects (mostly for unit tests)
In my opinion it has simple implementation so if you like its API, you can try use it too
rosie - nice library, good intuitive API.
if you write on JavaScript, it should solve all your needs.
The main drawback is typings. This library has @types/rosie
but it uses "builder" pattern which not allows to strong type checking between factory and target interface
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Please make sure to update tests as appropriate.
For more details see development guide