Testing the Controller

Recall how we implemented the registerUser controller.

File: src/controllers/auth/registerUser.js

const catchExceptions = require('../../utils/catchExceptions')
const globalResponseDto = require('../../responses/globalResponseDto')
const userResponseDto = require('../../responses/userResponseDto')
const registerUserRequestDto = require('../../requests/registerUserRequestDto')
const registerUserValidator = require('../../validators/registerUserValidator')
const authService = require('../../domain/services/auth.service')
const EventEmitter = require('events')
const eventEmitter = new EventEmitter()

/**
 * Inserts the user into the database and fires off an email notification to that user's email if successful.
 */
const registerUser = catchExceptions(async (req, res) => {
  const registerUserRequest = registerUserRequestDto(req.body)

  registerUserValidator(registerUserRequest)

  const user = await authService.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.

File: src/controllers/auth/__tests__/registerUser.test.js

const registerUserController = require('../registerUser')

const registerUserRequestDto = require('../../../requests/registerUserRequestDto')
const registerUserValidator = require('../../../validators/registerUserValidator')
const authService = require('../../../domain/services/auth.service')

jest.mock('../../../requests/registerUserRequestDto', () =>
  jest.fn((data) => data)
)
jest.mock('../../../validators/registerUserValidator', () =>
  jest.fn((data) => data)
)
jest.mock('../../../domain/services/auth.service', () => {
  return {
    registerUser: jest.fn((data) => data)
  }
})
const mockRequest = () => ({
  body: {
    first_name: 'john',
    last_name: 'doe'
  }
})

const mockResponse = () => {
  const res = {}

  res.status = jest.fn().mockReturnValue(res)
  res.json = jest.fn().mockReturnValue(res)

  return res
}

describe('Controler - Register User', () => {
  test('User should be registered successfully', async () => {
    const req = mockRequest()
    const res = mockResponse()

    await registerUserController(req, res)

    const randomUserFromBodyRequest = {
      first_name: 'john',
      last_name: 'doe'
    }

    expect(registerUserRequestDto).toHaveBeenCalledWith(
      randomUserFromBodyRequest
    )

    expect(registerUserValidator).toHaveBeenCalledWith(
      randomUserFromBodyRequest
    )

    expect(authService.registerUser).toHaveBeenCalledWith(
      randomUserFromBodyRequest
    )

    expect(res.status).toHaveBeenCalledWith(201)
    expect(res.json).toHaveBeenCalled()
  })
})

Last updated