Jest/TypeORM 在所有测试后清除数据库

Jas*_*der 15 javascript testing jestjs typeorm

我想在所有笑话测试之后或之前删除数据库中的所有条目。

这是我的 setup.js:

import { getConnection, getConnectionManager } from "typeorm"

beforeAll(async () => {
    const connectionManager = getConnectionManager()
    const connection = connectionManager.create({
        "type": "postgres",
        "host": "localhost",
        "port": 54320,
        "username": "test",
        "password": "test",
        "database": "test",
        "entities": ["../src/entities/*.ts"],
        "logging": false,
        "synchronize": true
    })
    await connection.connect()
})

afterAll(async () => {
    await getConnection().close()
})
Run Code Online (Sandbox Code Playgroud)

我在 typeorm 文档中读到,“同步”选项会用空的新表覆盖旧表,但它似乎不起作用。

这是我所做的测试:

describe('POST /create', () => {
    it('Create a user', async () => {
        const user: IStringTMap<string> = {
            firstName: 'John',
            lastName: 'Doe',
            email: 'john.doe@test.com',
            password: 'test123!',
        }

        const res: Response = await request(app)
            .post('/create')
            .send(user)
            .expect(200)

        expect(res.type).toEqual('application/json')
        expect(res.body.email).toBe('john.doe@test.com')
        expect(res.body.password).toBe(undefined)
    })
})
Run Code Online (Sandbox Code Playgroud)

第一个yarn test有效,但下一个无效(电子邮件已存在)

任何想法?

Mic*_*iel 19

也许有点晚了,但也在寻找这个,这就是我想到的。

这只会删除实体内部的内容,而不是实体本身。

afterEach(async () => {

    // Fetch all the entities
    const entities = getConnection().entityMetadatas;

    for (const entity of entities) {
        const repository = getConnection().getRepository(entity.name); // Get repository
        await repository.clear(); // Clear each entity table's content
    }
});
Run Code Online (Sandbox Code Playgroud)

编辑:如果您使用外键,请确保将该{onDelete: "CASCADE"}属性添加到您的列中,以便正确删除所有记录。

有关更多信息,请访问:https://github.com/typeorm/typeorm/issues/1460#issuecomment-366982161


yol*_*RAC 7

这是一种使用 typeorm 完全清理数据库的简单而有效的方法,创建一个专用的 TestService,在一个命令中截断所有实体:

import { Inject, Injectable } from "@nestjs/common";
import { Connection } from "typeorm";

@Injectable()
export class TestService {
  constructor(@Inject("Connection") public connection: Connection) {}

  public async cleanDatabase(): Promise<void> {
    try {
      const entities = this.connection.entityMetadatas;
      const tableNames = entities.map((entity) => `"${entity.tableName}"`).join(", ");
      
      await this.connection.query(`TRUNCATE ${tableNames} CASCADE;`);
      console.log("[TEST DATABASE]: Clean");
    } catch (error) {
      throw new Error(`ERROR: Cleaning test database: ${error}`);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以在测试文件中调用这个函数:

beforeEach(async () => {
  await testService.cleanDatabase();
});
Run Code Online (Sandbox Code Playgroud)