【问题标题】:Integration Test with TypeORM使用 TypeORM 进行集成测试
【发布时间】:2020-02-17 03:37:23
【问题描述】:

我正在通过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】:

    看起来 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();
    })
    
    

    【讨论】:

      猜你喜欢
      • 2022-06-15
      • 2013-04-07
      • 2019-12-17
      • 2015-12-28
      • 2020-05-26
      • 2018-01-02
      • 2021-02-03
      • 2015-06-14
      • 2018-12-23
      相关资源
      最近更新 更多