1.3.0 • Published 5 months ago

factory-box v1.3.0

Weekly downloads
-
License
MIT
Repository
github
Last release
5 months ago

factory-bot

The factory lib to create seed data for testing easily

Install

npm install factory-box

Usage

Define factory

// user.factory.ts

 define(UserEntity, (f: Factory) => {
    f.trait('withPosts', async (user: UserEntity) => {
        user.posts = await factory(PostEntity).saveMany(3, { title: 'Post title', body: 'Post body' });
    });

    f.trait('withAdmin', (user: UserEntity) => {
        user.role = 'admin';
    });

    f.build((options: Record<string, any>) => {
        const user = new UserEntity();

        user.id = options.id || 1;
        user.name = options.name || 'John Doe';
        user.email = options.email || 'example@gmail.com';

        return user;
    });
});

Create data

Apply trait

const user = await factory(UserEntity).withTraits('withAdmin').saveOne();

Override properties

const user = await factory(UserEntity).
    saveOne({
        email: 'override_email@example.com'
    });