Seeding test data in TypeORM

Seeding test data in TypeORM

We've created database entities so far that TypeORM can use to build SQL tables. Let's start by adding some data to the database. This could be done manually, but it would be tiresome; we need to adequately automate it so that we can have it up and running right away. The process can be made simpler by using the typeorm-seeding package to generate factories and seeders for our entities. Take the following actions.

Return to your terminal and issue the following command to start installing the package:

npm install typeorm-seeding 

Install the type definitions of the Faker library and create the src/database/, database/seeds/, and database/factories/ folders:

npm install -D @types/faker 
cd src/ && mkdir database  
cd database && mkdir seeds factories 

To run the seed commands, add the following scripts to the package.json file:

"scripts": { 
  "seed:config": "ts-node ./node_modules/typeorm-seeding/dist/cli.js config", 
  "seed:run": "ts-node ./node_modules/typeorm-seeding/dist/cli.js seed", 
  [...] 
} 

To make it simpler for you to dump and sync the database, add the following commands to the package.json file:

"scripts": { 
  "schema:drop": "ts-node ./node_modules/typeorm/cli.js schema:drop", 
  "schema:sync": "ts-node ./node_modules/typeorm/cli.js schema:sync", 
  […] 
} 

  • Date: