factory-t
TypeScript icon, indicating that this package has built-in type declarations

0.3.1 • Public • Published

factory-t


We can’t be silent! #SavePandaDoc

build/tests David (path) npm codecov

Quality Gate Status Bugs Technical Debt Code Smells

Maintainability

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

Goals

  • 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

Install

npm install factory-t

Usage

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

Status

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

Similar projects

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

Contributing

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

License

MIT

Package Sidebar

Install

npm i factory-t

Weekly Downloads

49

Version

0.3.1

License

MIT

Unpacked Size

46.8 kB

Total Files

31

Last publish

Collaborators

  • rodmax