Better test readability

An analysis of an e2e test & a more readable way to write them.

If we look at the file test -> domain -> users.e2e-spec, some overall similarities can be noticed with the unit tests. But now there is a variable for the app itself, and instead of obtaining references from within the module, it is used to initialize the app. Also notice that just below, that default route that was created with the project is being tested. The test's name includes the route's path and its associated HTTP method. Then, the request from the supertest library is used to simulate an actual request. It uses the server from the app in order to access the route with its HTTP method and, finally, expects a certain status and body.

Very well! But before actually modifying this test file to accomodate user-related tests, let's make some improvements to its readability so that we can use this style afterwards. Let's then perform the following:

  • Below the app variable, create a variable for the server

let server: HttpServer;
  • Obtain its reference after the app.init() call

server = app.getHttpServer();
  • In the module, import just the UsersModule instead of the entire AppModule

imports: [UsersModule],

Then, in the test, we shall:

  • Use the server variable

  • Put the result of the request() call in a response (and add an await)

  • Extract the status and body from the response

  • Use the enum for the status instead of its code number

  • Separate the expects from the request() call

Now, this is much more readable.

it('/ (GET)', async () => {
  const response = await request(server).get('/');
  const { status, body } = response;

  expect(status).toBe(HttpStatus.OK);
  expect(body).toBe('Hello World!');
});

Let's then have an environment that resembles a real-world context before going to the tests.

Last updated