0Pricing
NestJS Enterprise Backend APIs · 课时

数据库填充与测试

学习使用初始数据填充数据库,以满足开发和测试需求,确保环境一致。

数据库填充与测试 是 CoddyKit 上的免费 NestJS Enterprise Backend APIs 课时。 这是第 3 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 NestJS Enterprise Backend APIs 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 NestJS Enterprise Backend APIs 课程共包含 3 节课。

本课时的部分内容尚未翻译,以英文显示。

What is Database Seeding?

Imagine starting a new project or running tests. Your database is empty! Database seeding is the process of populating a database with initial data.

This data can be anything from default user accounts to sample product listings. It's crucial for development, testing, and even for setting up a production environment with essential configuration data.

Benefits of Seeding

Seeding offers several key advantages:

  • Consistent Environments: Ensures everyone on the team, and your CI/CD pipeline, works with the same baseline data.
  • Faster Development: Developers don't waste time manually entering test data.
  • Reliable Testing: Tests run against predictable data, making results more trustworthy.
  • Easier Onboarding: New team members can quickly set up their local environment with meaningful data.

NestJS & TypeORM Seeding

In a NestJS application using TypeORM, seeding typically involves creating dedicated scripts that interact with your TypeORM entities and repositories.

While TypeORM itself has a CLI for migrations, for seeding, you often create custom scripts that can be run on demand. These scripts use TypeORM's EntityManager or specific repositories to insert data.

Crafting a Simple Seeder

Let's look at a conceptual example of a seeder script. This script would usually live in a src/database/seeds directory and be executed via a custom npm script.

It uses TypeORM's Repository to create and save a new user, ensuring the data is persisted correctly.

// src/database/seeds/user.seeder.ts
import { DataSource } from 'typeorm';
import { User } from '../../users/user.entity';
import { Seeder, SeederFactoryManager } from 'typeorm-extension';

export default class UserSeeder implements Seeder {
  public async run(
    dataSource: DataSource,
    factoryManager: SeederFactoryManager
  ): Promise<any> {
    const userRepository = dataSource.getRepository(User);

    // Check if user already exists to prevent duplicates
    let adminUser = await userRepository.findOneBy({ email: 'admin@example.com' });

    if (!adminUser) {
      adminUser = userRepository.create({
        firstName: 'Admin',
        lastName: 'User',
        email: 'admin@example.com',
        password: 'securePassword123', // In real app, hash this!
      });
      await userRepository.save(adminUser);
      console.log('Admin user seeded.');
    } else {
      console.log('Admin user already exists.');
    }
  }
}

Executing Seeder Scripts

To run your seeders, you typically add a custom script to your package.json. You might use ts-node to execute TypeScript files directly, or compile them first.

A common setup involves a typeorm-extension library which provides a more structured way to manage and run seeders, similar to how migrations are handled.

// package.json snippets
{
  "scripts": {
    "seed:run": "ts-node -r tsconfig-paths/register ./node_modules/typeorm-extension/dist/cli/index.js seed -d src/config/typeorm.config.ts"
  }
}

Development Data

For development, seeding often means populating your database with a good amount of realistic-looking data. This helps you test UI components, pagination, and search functionality without manually creating hundreds of entries.

You might use libraries like Faker.js (or @faker-js/faker) within your seeders to generate diverse and random data for users, products, posts, etc.

Test-Specific Data

When it comes to testing, seeding takes on a more precise role. You often need very specific, controlled datasets for your unit and integration tests.

For example, a test for a login feature might only need one specific user record, not hundreds. This ensures your tests are deterministic and don't break due to unexpected data.

Seeding in Test Workflows

To ensure a clean slate for each test run, it's a common practice to run seeders before or after your tests. Jest, a popular testing framework, allows you to define setup and teardown functions.

You could use beforeEach or beforeAll to execute a seeding script, ensuring your database is in a known state before tests begin.

// Conceptual test file snippet
import { INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import { AppModule } from './app.module';
import { DataSource } from 'typeorm';
import UserSeeder from './database/seeds/user.seeder'; // Your seeder

describe('UsersController (e2e)', () => {
  let app: INestApplication;
  let dataSource: DataSource;

  beforeAll(async () => {
    const moduleFixture = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();

    app = moduleFixture.createNestApplication();
    await app.init();
    
    // Get TypeORM DataSource
    dataSource = app.get(DataSource);
  });

  beforeEach(async () => {
    // Clear database and run specific seeders before each test
    await dataSource.synchronize(true); // CAUTION: Clears all data! Use carefully.
    await new UserSeeder().run(dataSource, null); // Run your seeder
  });

  afterAll(async () => {
    await app.close();
  });

  it('/users (GET) should return seeded users', () => {
    // Test logic here, expecting seeded data
  });
});

Key Seeding Practices

Follow these tips for robust seeding:

  • Idempotency: Ensure running a seeder multiple times doesn't create duplicate data unless intended. Check for existing records first.
  • Clear Separation: Keep development seeders (lots of dummy data) separate from testing seeders (minimal, precise data).
  • Version Control: Store seeders in your version control system.
  • Environment-Specific: Be cautious when running seeders in production. Only seed essential config data.

Seeding Benefits

Database seeding provides significant advantages for development and testing.

Which of the following are primary benefits of database seeding?

Recap: Seeding for Success

Congratulations! You've learned about database seeding, a vital practice for any backend developer.

We covered what seeding is, its benefits for development and testing, and how to implement and run seeders in a NestJS/TypeORM application. You also saw how to integrate seeding into your test workflows.

By mastering seeding, you ensure consistent, reliable, and efficient development and testing cycles!

常见问题解答

「数据库填充与测试」课时是免费的吗?

是的 — 「数据库填充与测试」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 NestJS Enterprise Backend APIs 课程的其余内容,请升级到 CoddyKit PRO。 NestJS Enterprise Backend APIs 课程共包含 3 节课。

「数据库填充与测试」这节课中我会学到什么?

学习使用初始数据填充数据库,以满足开发和测试需求,确保环境一致。 你通过在浏览器中直接运行的动手代码来练习 NestJS Enterprise Backend APIs,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 NestJS Enterprise Backend APIs 需要有经验吗?

无需任何先前经验。CoddyKit 上的 NestJS Enterprise Backend APIs 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 3 节。

「数据库填充与测试」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 NestJS Enterprise Backend APIs 课中编写并运行代码吗?

能。每节 NestJS Enterprise Backend APIs 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 自定义 TypeORM 存储库
  2. 事务与迁移
  3. 数据库填充与测试
← 返回 NestJS Enterprise Backend APIs