E2E NestJs testing with jest cannot split file

Let say I have test file like bellow

test.spec.ts

import { INestApplication } from '@nestjs/common'
import * as request from 'supertest'
import server from './src/main' //server is bootstrap()
let app: INestApplication

describe('Application', () => {
  beforeAll(async () => {
    app = await server
  })

  it('Application should be defined', async () => {
    expect(app).toBeDefined()

  })

  it('World module', async () => {
    request(app.getHttpServer())
      .get('/api/worlds')
      .expect(200)
  })

  afterAll(async () => {
    await app.close()
  })
})

when I run test, everything works fine but when I split World endpoints to new file like

world.module.spec.ts

import { INestApplication } from '@nestjs/common'
import * as request from 'supertest'
export default function TestWorldModule(app: INestApplication) {
  it('/api/worlds', () => {
    return request(app.getHttpServer()) //Throw error here app is undefined
      .get('/api/worlds')
      .expect(200)
  })
}

and Import TestWorldModule in test.spec.ts

describe('Application', () => {
  ...

  TestWorldModule(app)

  ...
})

It throws an error app is undefined.

Where did I do wrong?

  • Show the full error, and how you created app in test.spec.ts

    – 

Leave a Comment