How can I use one app instance for all my e2e tests?

Viewed 311

I'm working in a nestjs project that is organized into separate modules. Each module has it's own e2e test. Inside each of these tests an instance of the application is created in the beforeAll() method. Like this

const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [
        AppModule,
      ],
    }).compile();

    app = moduleFixture.createNestApplication();
    await app.init();

At the end of the test the app.close() is called tearing down the app.

Is there a way I can use the same app for all of my tests and then just shut the app down at the end? Creating and tearing down the entire app for each test makes the e2e tests take a long time. Also I'm running into Async timeout errors.

1 Answers

After many trials, I found out that this was impossible because:

Every test runs in its own environment

Let me elaborate:

1. You cannot setup app instance in globalSetup, because:

Note: Any global variables that are defined through globalSetup can only be read in globalTeardown. You cannot retrieve globals defined here in your test suites.

Which means that you cannot use one global.app variable across test cases. If you cannot share global.app variable, then you cannot use request(app.getHttpServer()), which is essential for e2e tests.

2. You can setup app instance in setupFiles or setupFilesAfterEnv but these files will be running per each test case. This is clearly against the intention

Each setupFile will be run once per test file. Since every test runs in its own environment, these scripts will be executed in the testing environment before executing setupFilesAfterEnv and before the test code itself.

The document doesn't say setupFileAfterEnv will be run per test file. So I tried, but unfortunately, it ran per test file.

Related