测试套件之间的NestJS Share e2e服务器

时间:2019-10-23 07:53:04

标签: typescript mocha nestjs

我正在使用NestJS测试模块来模拟Nest应用,并且希望在各种测试套件中共享该应用。
这是我的设置:

test
  |_ helpers
    |_ testApp.ts
  |_ e2e
    |_ users.e2e-test.ts
  |_ beforeAll.e2e-test.ts

testApp.ts

import { Test } from '@nestjs/testing';
import { DatabaseModule } from '../../src/database/database.module';
import { UserModule } from '../../src/user/user.module';

let app: any;
export async function initServer() {
  const fixture = await Test.createTestingModule({
    imports: [
      DatabaseModule,
      UserModule,
    ],
  }).compile();
  app = fixture.createNestApplication();

  await app.init();
}
export default app;

beforeAll.e2e-test.ts

import { initServer } from './helpers/testApp';

before(async () => {
  await initServer();
});

users.e2e-test.ts

import * as request from 'supertest';
import * as chai from 'chai';
const expect = chai.expect;

import { UserType } from '../../src/user/enum/user-types.enm';
import app from '../helpers/testApp';

const admin = {
  email: 'admin@example.com',
  password: '123',
  type: UserType.ADMIN
};
describe.only('Creating User with customized permissions', async () => {
  it('User should be able to sign in', async () => {
    request(app.getHttpServer())
      .post('/auth/signin')
      .send({ email: admin.email, password: '123' })
      .end((_, res) => {
        expect(res.status).to.equal(200);
      });
  });
});

因此,基本上我想在各种测试套件中共享NestApplication实例,但是在测试用例中,我得到的appundefined,它给出了以下错误:
TypeError: Cannot read property 'getHttpServer' of undefined

有没有办法做到这一点?还是应该在每个测试套件中初始化一个新的NestApplication

我正在使用mocha作为测试跑步者。

1 个答案:

答案 0 :(得分:0)

尝试一下。

beforeAll(async () => {
  const module = await Test.createTestingModule({
    providers: [
      MyTestsService,
      {
        provide: getRepositoryToken(Warehouse),
        useValue: myTestsService
      }
    ],
    controllers: [MyTestsController], // <-- this will fix problem of getHttpServer
  })
    .overrideProvider(MyTestsService)
    .useValue(myTestsService)
    .compile();

  app = module.createNestApplication();
  await app.init();
});