TypeORM集成测试

问题描述 投票:1回答:1

我正在通过Supertest向我的开发服务器发出请求来进行集成测试。但是我对如何将数据放入数据库有麻烦。例如,在运行GET测试之前,我想将数据插入数据库。但我什至无法从TypeORM获得连接:

ConnectionNotFoundError: Connection "default" was not found.

如果我什至从TypeORM获得连接,完成测试后如何将测试包装在事务中并回滚事务以确保集成测试不会影响真实数据库。

基本上,是否有与Rails的factory_bot类似的软件包?

describe("Templates", (): void => {
  describe("GET /api/v1/templates/{templateHash}", (): void => {
    let template: Template;
    beforeEach(
      async (): Promise<void> => {
        let templateService: TemplateService = new TemplateService();
        let connection: Connection = getConnection("default");
        template = new Template(Buffer.from(faker.random.words()), faker.random.uuid(), faker.system.fileName());
        await templateService.create(connection, template);
      },
    );
    it("should return a template", (done): void => {
      request(config.devEnvEndpoint)
        .get(`api/v1/templates/${template.templateHash}`)
        .set("Accept", "application/json")
        .expect(200)
        .end((err, response): void => {
          console.log(response);
          done();
        });
    });
  });
});

node.js typescript integration-testing typeorm
1个回答
0
投票
通过拥有两个数据库,您不必担心事务,可以在测试之间删除数据库。我想事务处理会更快,但实际上取决于您的用例(我注意到进行很多connection.synchronize()调用时测试速度要慢得多。

然后您可以使用环境变量来确定要实例化的连接:

// db.ts import { Connection, createConnection } from 'typeorm' let connection: Connection | null = null export async function getConnection() { if (connection) { return connection; } // DATABASE_CONFIG can be 'development' or 'test' // and should correspond to the connection names // in the ormconfig.json file connection = await createConnection(process.env.DATABASE_CONFIG); return connection; } export async function closeConnection() { await connection?.close(); }

然后您可以设置环境变量并运行测试:

// DATABASE_CONFIG=test yarn test
import { getConnection, closeConnection } from './db'

let connection: Connection;

beforeAll(async () => {
  connection = await getConnection();
});

beforeEach(async () => {
  // Drop everything and recreate db
  await connection.synchronize(true);
});

afterAll(async () => {
  await closeConnection();
});

it('should create a connection', () => {
  expect(connection).toBeDefined();
})

© www.soinside.com 2019 - 2024. All rights reserved.