使用 Jest 和 TypeORM 进行测试

2025-06-04

使用 Jest 和 TypeORM 进行测试

大家好!

因此,今天我将向您展示如何配置代码以使用 TypeORM 和 Jest 进行测试。

模块

首先,让我们在 Node 环境中安装一些模块。我使用 Yarn:

yarn add jest ts-jest @types/jest -D

yarn add typeorm typescript pg

然后,让我们创建 tsconfig 文件:
yarn tsc --init

Jest 配置

好的,现在我们需要配置我们的 jest.config.js,以下是我的配置:

module.exports = {
  clearMocks: true,
  maxWorkers: 1,
  preset: 'ts-jest',
  testEnvironment: 'node',
  testMatch: [
    '**/__tests__/**/*.[jt]s?(x)',
    '!**/__tests__/coverage/**',
    '!**/__tests__/utils/**',
    '!**/__tests__/images/**',
  ],
};

我喜欢在项目根目录中创建一个名为tests的目录来进行测试。

TypeORM 配置

我喜欢创建 ormconfig.js。也可以创建 .json 或 .env 文件。

module.exports = {
  name: 'default',
  type: 'postgres',
  host: 'localhost',
  port: 5432,
  username: 'postgres',
  password: 'postgres',
  database: 'tests',
  dropSchema: true,
  logging: false,
  synchroize: true,
  migrationsRun: true,

  entities: ['src/database/entities/*.ts'],
  migrations: ['src/database/migrations/*.ts'],
  cli: {
    entitiesDir: 'src/database/entities',
    migrationsDir: 'src/database/migrations',
  },
};

因此,dropSchema: true因为这会在测试后删除您的数据。

我喜欢让它migrationsRun: true在测试之前自动运行迁移。

我正在使用 postgres,但您也可以使用自己喜欢的数据库。

创建连接文件

让我们创建一个 connection.ts 来导出一些函数以在我们的测试中运行。

import {createConnection, getConnection} from 'typeorm';

const connection = {
  async create(){
    await createConnection();
  },

  async close(){
    await getConnection().close(); 
  },

  async clear(){
    const connection = getConnection();
    const entities = connection.entityMetadatas;

    entities.forEach(async (entity) => {
      const repository = connection.getRepository(entity.name);
      await repository.query(`DELETE FROM ${entity.tableName}`);
    });
  },
};
export default connection;

清除方法将删除我们连接中注册的每个实体的所有数据。

创建测试

因此,在您的测试中,只需输入以下代码:

import connection from '../src/connection';

beforeAll(async ()=>{
  await connection.create();
});

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

beforeEach(async () => {
  await connection.clear();
});

it('creates a user', () => {
  // TODO
})

就是这样:)

Github项目

如果你想查看完整的项目,请点击此处

文章来源:https://dev.to/caiulucas/tests-with-jest-and-typeorm-4j1l
PREV
WebRTC - The technology that powers Google Meet/Hangout, Facebook Messenger and Discord History of Real-time Communication Overview Why do developers & companies love Web RTC? What happens during the P2P connection Signaling Network Address Translations (NATs) and ICE STUN Servers Limitations - Symmetric NAT Why STUN servers are useful TURN Servers VP9 Video Codec JavaScript APIs Security Applications that use WebRTC
NEXT
身份验证与授权