Recall how we implemented the registerUser controller.
File: src/controllers/auth/registerUser.js
constcatchExceptions=require('../../utils/catchExceptions')constglobalResponseDto=require('../../responses/globalResponseDto')constuserResponseDto=require('../../responses/userResponseDto')constregisterUserRequestDto=require('../../requests/registerUserRequestDto')constregisterUserValidator=require('../../validators/registerUserValidator')constauthService=require('../../domain/services/auth.service')constEventEmitter=require('events')consteventEmitter=newEventEmitter()/** * Inserts the user into the database and fires off an email notification to that user's email if successful. */constregisterUser=catchExceptions(async (req, res) => {constregisterUserRequest=registerUserRequestDto(req.body)registerUserValidator(registerUserRequest)constuser=awaitauthService.registerUser(registerUserRequest)eventEmitter.emit('userHasRegistered', user)res.json(globalResponseDto({ status:'success', code:200, message:`The email: ${registerUserRequest.email} has successfully registered.`, data:userResponseDto(user), errors:null }) )})module.exports= registerUser
The Test
Now because our controller has been kept nice and thin up until this point and have barely any logical statements other than the functions and services we've created, there's actually very little to test. If you've done your job correctly, then you should not have to test the controller what so ever because all of your tests would have been done in those other layers.
However, since this is an educational book, we will do it for demonstration purposes.
In order to test the controller, the key is to mock every service that its using and see if they've been called or not.
Check out the following test case as we mock the registerUserRequestDto, the registerUserValidator, the authService.register function, and the express req and res.