代码之家  ›  专栏  ›  技术社区  ›  Zameer Ansari

如何在单元测试中使用TypeORM全局创建connection()?

  •  0
  • Zameer Ansari  · 技术社区  · 5 年前

    我有一个 node.js application inside TypeORM's createConnection() body

    // index.ts
    import { createConnection } from "typeorm";
    createConnection().then(async connection => {
        // express app code here
    }).catch(error => console.log(error));
    

    jest

    // abc.test.ts
    createConnection().then(async connection => {
    
        describe('ABC controller tests', () => {
            it('should test abc function1', async () => {
                // test body does here                
            });       
        });
    }).catch(error => console.log(error));
    

    • 这是我第一次使用TypeORM,所以我没有任何实践经验
    • 它甚至都不起作用 SyntaxError: Cannot use import statement outside a module
    • 看起来这是一个非常丑陋的方法
    • 我只想在一个地方生成连接代码,不是在每个测试文件中,但是没有 入口点 对于像应用程序这样的测试 index.ts

    如何在单元测试中使用TypeORM全局创建connection()?

    2 回复  |  直到 5 年前
        1
  •  3
  •   UroÅ¡ Anđelić    5 年前

    你应该用 beforeEach afterEach

    describe('ABC controller tests', () => {
        let connection: Connection
    
        beforeEach(async () => {
          connection = await createConnection()
        })
    
        it('should test abc function1', async () => {
            connection.doSomething()
        })
    
        afterEach(async () => {
            await connection.close()
        })
      })
    
        2
  •  1
  •   Teneff    5 年前

    你应该能够创造

    jest.setup.js (setupFilesAfterEnv)
    // Promise<Connection>
    global.connection = createConnection()
    

    然后你就可以等待承诺在你的测试中得到解决

    abc.test.ts
    describe('abc', () => {
      beforeAll(async () => {
        await global.connection
      });
    
      it('should be connected', () => {
        // not sure if that property really exists
        expect(global.connection).toHaveProperty('isConnected', true)
      })
    })