使用TypeORM进行集成测试

3

我正在通过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();
        });
    });
  });
});

1个回答

2
看起来typeorm没有读取到您的配置。建议使用ormconfig.json文件并设置两个数据库配置——一个用于开发,一个用于测试。
拥有两个数据库,您不需要担心事务,也可以在测试之间删除数据库。我猜事务可能会更快,但这真的取决于您的用例(当进行大量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();
})


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接