0

I have a 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));

Now, I wanted to write unit test cases using jest and I wanted the connection to be available across the tests

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

I have a few concerns:

  • This is my first time working with TypeORM, so I don't have any hands-on experience on it
  • It doesn't even work & throws SyntaxError: Cannot use import statement outside a module
  • It looks like a very ugly approach
  • I wanted the connection making code at only one place, not in every test file but there is no entry point for tests like the app has index.ts

How to globally createConnection() with TypeORM in unit tests?

Zameer Ansari
  • 28,977
  • 24
  • 140
  • 219
  • 1
    Yesterday I wrote an answer about this error [here](https://stackoverflow.com/questions/62200568/syntaxerror-cannot-use-import-statement-outside-a-module-when-writing-test-wi) – Teneff Jun 06 '20 at 05:56
  • @Teneff error is only part of the problem - I wanted to know how to globally create the connection! Btw, thanks for the help! The error is gone now! – Zameer Ansari Jun 06 '20 at 06:00

2 Answers2

3

You should use beforeEach and afterEach to set up your state/context/world. Something like:

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()
    })
  })
Uroš Anđelić
  • 1,134
  • 7
  • 11
1

You should be able to create

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

and then you can await the Promise to be resolved in your tests

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)
  })
})
Teneff
  • 30,564
  • 13
  • 72
  • 103