Recall how we implemented the userRepository in one of the earlier chapters.
File: src/domain/repositories/user.repository.js
constUserModel=require('../models/user.model')/** * * @param{*} user { * - name * - email * - password * } * * @returns user */constcreateUser=async (userData) => {constuser=newUserModel(userData)constuserReturn=awaituser.save(userData)return userReturn}module.exports= { createUser}
Now it's time to write out test cases.
For testing repositories, what we are mainly interested in is if the database operations are working. For that to work, we'll have to arrange to connect to the database on every test.
Here we have a couple of helpers that will help us test for database-based test cases. The db function let's us create a connection to the database, it's simply a wrapper around the mongoose database driver, that is why you see a disconnect function in the afterAll function. We then have a dbTestUtils object that has a clearDatabase function which allows us to reset the database and let's us start off from a clean slate. For a closer look at what those helper functions do, you can dive deeper by looking at the source code of the repository.
Now Moving on to the first successful test case, we have the following. We are simply calling the createUser method and passing in all of the necessary fields. This is a nice, clean, and simple test.
For the failing test case, we can decide to not pass in certain required fields. Recall that our UserModel had certain required fields when we created it.
Here is what a possible failing test case would look like.
Although this seems a little redundant due to the fact that we already have validation in another layer, this is simply to illustration how one might go about writing tests for a repository layer. When you start creating more complicated repositories that use multiple different models, you'll find more complicated tests are needed.
Service
Recall how we implemented the authService in one of the earlier chapters.
The service layer is going to be all about us mocking out the repository layer. We do so in order to keep the tests as separate and isolated as possible.
For a successful test case, take a look at the following. We do a simple mock of both the userRepository and its method createUser functions and see if they've been called properly.