Currently, I'm utilizing the NestJS test module to simulate the nest app for testing purposes and my goal is to make this app accessible across various test suites.
Here is how I have set it up:
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: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3c5d585155527c59445d514c5059125f5351">[email protected]</a>',
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);
});
});
});
My main objective is to share the NestApplication
instance among different test suites. However, I am encountering an issue where the app
is showing up as undefined
in the test case, resulting in the error message:
TypeError: Cannot read property 'getHttpServer' of undefined
Is there a solution or workaround for this problem? Should I initialize a new NestApplication
for each test suite?
Just to give you more context, I am utilizing mocha
as my test runner.