Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@os-team/typeorm-seeder

oxilor37MITdeprecated1.0.17TypeScript support: included

Unsupported. Migrated to slonik. See @os-team/slonik-seeder.

Simple seeder for seeding data in tests using TypeORM.

readme

@os-team/typeorm-seeder NPM version

Simple seeder for seeding data in tests using TypeORM.

Usage

Install the package in devDependencies (-D) using the following command:

yarn add -D @os-team/typeorm-seeder

Example of test

import 'reflect-metadata';
import { Connection, createConnection } from 'typeorm';
import createSeeder, { Seeder } from '@os-team/typeorm-seeder';
import User from '../../entities/User';
import Payment from '../../entities/Payment';

let connection: Connection;
let seeder: Seeder;

beforeEach(async () => {
  connection = await createConnection();
  seeder = createSeeder(connection.manager); // Create the seeder
});

afterEach(async () => {
  await connection.close();
});

it('Should change the payment status to succeeded', async () => {
  // Seed a user
  const userData = {
    id: 1,
    name: 'name',
  };
  await seeder.seed(User, userData);

  // Seed payments
  await seeder.seed(Payment, [
    {
      id: 1,
      amount: 1000,
      status: 'pending',
      user: { id: userData.id },
    },
    {
      id: 2,
      amount: 2000,
      status: 'pending',
      user: { id: userData.id },
    },
  ]);

  // ...
});

Most likely you will use multiple test files (e.g. one test file for testing one API method). In this case:

  1. Put beforeEach, afterEach and global variables (connection, seeder) to a separate file. Export the seeder variable to use it in any test file.
  2. Add the path to this file to setupFilesAfterEnv. Jest will run this code before each test file in the suite is executed.
  3. Set the dropSchema option in the TypeORM config to true ONLY in the test environment. TypeORM drops the schema each time connection is being established (before each test file). See more about TypeORM connection options.