【问题标题】:Jest/TypeORM purge database after all tests在所有测试后 Jest/TypeORM 清除数据库
【发布时间】:2019-11-09 12:36:33
【问题描述】:

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

这是我的 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()
})

我在 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)
    })
})

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

有什么想法吗?

【问题讨论】:

    标签: javascript testing jestjs typeorm


    【解决方案1】:

    可能有点晚了,但也在寻找这个,这就是我想出的。

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

    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
        }
    });
    

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

    更多信息可以在这里找到:https://github.com/typeorm/typeorm/issues/1460#issuecomment-366982161

    【讨论】:

    • 您将无法使用此代码清除依赖于另一个实体的实体。
    • 没错,我没有在我的数据库中使用显式外键。这是因为我有一个微服务架构。
    • 推送了一个编辑以使其与外键一起工作。
    【解决方案2】:

    您可以在您的 e2e 测试文件中使用单独的名称设置一个新数据库,并在导入 typeorm 模块时设置dropSchema: true 选项。您可以像在 AppModule 中一样导入 typeorm 模块

    【讨论】:

      【解决方案3】:

      您可能不必为此测试清除数据库。您也可以使用 faker 之类的库并绕过电子邮件重复验证。 Faker 将在每次测试运行时产生一个唯一的用户。将您的用户更改为:

      
      import fake from 'faker';
      
      const user: IStringTMap<string> = {
        firstName: faker.name.firstName(),
        lastName: faker.name.lastName(),
        email: faker.internet.email(),
        password: faker.internet.password()
      }
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-07
        • 2014-04-30
        • 1970-01-01
        相关资源
        最近更新 更多