Skip to content
Advertisement

Start and stop server with supertest

I have the following server class :

JavaScript

I’m using supertest for end-to-end testing. I wish to start my application beforeAll tests and stop it when the tests are done.

It’s easy to do that using beforAll and afterAll where I can just once instanciate the Server class and call the start and close methods.

But as I have 10+ controllers to test, I want to avoid to start and stop the server during each test file.

I found on the documentation the setupFiles and setupFilesAfterEnv but I can’t stop the server since the instance is not “shared” in the two files.

This is an example of 1 test file :

JavaScript

This works totally fine but I’m duplicating this beforeAll and afterAll methods in every test file. Is there a way to declare it only once ?

Thanks

Advertisement

Answer

You could use setupFiles to set up test fixtures globally. You can assign variables that you want to use in multiple test files to Node.js global object.

E.g.

app.ts:

JavaScript

app.setup.js:

JavaScript

jest.config.js:

JavaScript

a.controller.test.js:

JavaScript

b.controller.test.js:

JavaScript

unit test results:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement