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
appvariable, create a variable for theserver
let server: App;Obtain its reference after the
app.init()call
server = app.getHttpServer();In the
module, import just theUsersModuleinstead of the entireAppModule
imports: [UsersModule],Then, in the test, we shall:
Use the
servervariablePut the result of the
request()call in aresponseExtract the
statusandbodyfrom theresponseUse the enum for the
statusinstead of its code numberSeparate the
expectsfrom therequest()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