Testing entire flows
It's time to finally implement our more realistic, e2e tests.
Now we can focus entirely on the test file. Back to it, first let's replace beforeEach()
with beforeAll()
, so that the app
is initialized just once instead of before each test. Let's also add an afterAll()
call at the bottom to clean up resources, such as close the database connection, etc.
Here, the 5 routes will be hit sequentially in the same database. Ergo, it will be verified if when:
Creating a
user
, it is created successfullySearching for all
users
, there is a single oneSearching for this
user
, it is foundUpdating this
user
, the field is changedRemoving this
user
, it no longer exists
To help us, let's put at the top of the file:
A fake
createUserDto
A fake
updateUserDto
An
expectedUser
The password
and phone
are hardcoded due to their validation rules (with phone
, you may need to adjust to you region).
Now, let's change the name of the describe()
to the resource being tested and its base path.
In the imports
of the module
, let's add the ConfigModule
so we can access the environment variables, and use the validation schema for testing. We should also specify the path for the appropriate .env file. We'll also connect to the database right after it.
And lastly, in the providers
, enable the ValidationPipe
and the NotFoundExceptionFilter
globally.
Now, remember that writing style we used in that default test? Let's then continue to use it and everything will be much simpler.
Beginning with the test for create()
, we shall
Access the /users route with POST
While sending the
createUserDto
in thebody
withsend()
Check if
The
status
is CREATEDThe
body
matches theexpectedUser
Note the following:
The
body
is typed as any, so we should perform the appropriate type assertionThe
toMatchObject()
matcher, which checks if an object contains some fields
In findAll()
, we
Access the /users route with GET
Check if
The
status
is OKThe
body
contains a single elementIt matches the
expectedUser
In findOne()
, there's nothing new.
In update()
, we just check if the name
was altered. The findOne()
is also used for checking this.
Finally, in remove()
, we also check if a findOne()
call will result in the status NOT FOUND.
And we're done! Just remember to delete that default test and then run the e2e tests.
Commit - Implementing e2e tests
Last updated