Testing the Validation

File: src/requests/registerUserValidator.js

const Validator = require('validatorjs')
const ApiException = require('../utils/ApiException')

/**
 * @param {*} data {
 *  - first_name
 *  - last_name
 *  - email
 *  - password
 *  - password_confirm
 *  - phone_number
 * }
 *
 * @returns Validator
 */
const registerUserValidator = (data) => {
  const rules = {
    first_name: 'required',
    last_name: 'required',
    email: 'required|email',
    password: 'required|min:6',
    password_confirmation: 'required|min:6|same:password',
    phone_number: 'required|telephone'
  }

  const validator = new Validator(data, rules)

  if (validator.fails()) {
    let errors = []
    for (const field in validator.errors.errors) {
      errors = errors.concat(validator.errors.errors[field])
    }

    throw new ApiException({
      status: 'error',
      code: 400,
      message: 'There were errors with the validation.',
      data: null,
      errors
    })
  }

  return validator
}

Validator.register(
  'telephone',
  function (value) {
    return value.match(/^\(?([0-9]{3})\)?[-.●]?([0-9]{3})[-.●]?([0-9]{4})$/)
  },
  'The :attribute field is not in a correct format.'
)

module.exports = registerUserValidator

File: src/validators/__tests__/registerUserValidator.test.js

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

describe('Test Suite: registerUserValidator.test.js', () => {
  test('The happy path - everything works', () => {
    // 1. Arrange
    const data = {
      first_name: 'John',
      last_name: 'Doe',
      email: 'johndoe@gmail.com',
      password: 'superduperpassword',
      password_confirmation: 'superduperpassword',
      phone_number: '1234567890'
    }

    // 2. Act
    const validator = registerUserValidator(data)

    // 3. Assert
    expect(Object.keys(validator.errors.errors).length).toEqual(0)
  })

  test('Not matching passwords', () => {
    // 1. Arrange
    const data = {
      email: 'johndoe@gmail.com',
      password: 'superduperpassword',
      password_confirmation: 'superduperpassword1'
    }

    // 2. + 3. Act and Assert
    expect(() => {
      registerUserValidator(data)
    }).toThrow(Error)
  })
})

Last updated