Testing the Request

Recall how we implemented the registerUserRequestDto.

File: src/requests/registerUserRequestDto.js

const path = require('path')
const ApiException = require('../utils/ApiException')

const fields = [
  'first_name',
  'last_name',
  'email',
  'password',
  'password_confirmation',
  'phone_number'
]

/**
 * @param Object data
 */
const registerUserRequestDto = (data) => {
  const errors = []
  fields.forEach((field) => {
    if (!(field in data)) {
      errors.push(`This DTO's property is required: ${field}.`)
    }
  })

  if (errors.length > 0) {
    throw new ApiException({
      status: 'error',
      code: 422,
      message: 'Input fields are of not the correct form.',
      data: null,
      errors
    })
  }

  return data
}

module.exports = registerUserRequestDto

We'll first setup our test suite.

We'll be working mainly in this file for the rest of this section.

File: src/requests/__tests__/registerUserRequestDto.test.js

const registerUserRequestDto = require('../registerUserRequestDto')

describe('Test Suite: registerUserRequestDto', () => {
  // tests go here...
})

I personally always like to write at least 1 test for both a passing and failing scenario.

Of course you can always write more tests to cover more additional scenarios and edge cases . For our purposes, we'll just be sticking to writing 1 passing test and 1 failing test.

The Passing Test

The first one is simple, let's add in all the required fields in registerUserRequestDto and expect what we want out of it.

test('Request 1 - all required fields', () => {
  // 1. Arrange
  const inputRequest = {
    first_name: 'Yichen',
    last_name: 'Zhu',
    email: 'yichen@yichen.com',
    password: 'yichen-and-his-awesome-password',
    password_confirmation: 'yichen-and-his-awesome-password',
    phone_number: '1234567890'
  }

  // 2. Act
  const registerUserRequest = registerUserRequestDto(inputRequest)

  // 3. Assert
  expect(registerUserRequest).toEqual({
    first_name: 'Yichen',
    last_name: 'Zhu',
    email: 'yichen@yichen.com',
    password: 'yichen-and-his-awesome-password',
    password_confirmation: 'yichen-and-his-awesome-password',
    phone_number: '1234567890'
  })
})

The Failing Test

The next test case is what happens if we don't pass the correct inputs into the registerUserRequestDto function. We would expect an error, and not just any error, but an ApiException error being thrown.

test('Request 2 - missing input fields', () => {
  // 1. Arrange
  const inputRequest = { message: 'this is awesome!' }

  // 2. Act + 3. Assert
  expect(() => {
    registerUserRequestDto(inputRequest)
  }).toThrow(ApiException)
})

Last updated