Testing the Response

Recall how we implemented the userResponseDto.

File: src/responses/userResponseDto.js

const userResponseDto = (user) => {
  return {
    id: user['id'],
    first_name: user['first_name'],
    last_name: user['last_name'],
    email: user['email'],
    phone_number: user['phone_number']
  }
}

module.exports = userResponseDto

You may look at this and feel a sense of déjà vu, and you would be right, because writing a test for the userResponseDto is quite similar to writing a test for the registerUserRequestDto.

As always we'll setup our test suite as follows.

File: src/responses/__tests/userResponseDto.test.js

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

describe('Test Suite: userResponseDto', () => {
  // Tests go here
})

The Tests

Since this is quite an easy function to test, let's add in some more test cases this time.

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

describe('Test Suite: Response', () => {
  test('Correct request 1 - empty parameters', () => {
    // 1. Arrange
    const user = {}

    // 2. Act
    const response = userResponseDto(user)

    // 3. Assert
    expect(response).toEqual({})
  })

  test('Correct request 2 - extra useless parameters', () => {
    // 1. Arrange
    const user = {
      id: '123',
      first_name: 'john',
      last_name: 'doe',
      email: 'johndoe@email.com',
      phone_number: '1234567890',
      password: 'undefined',
      extraParam1: null,
      extraParam2: 'whatzup',
      body: 'John Doe is cool'
    }

    // 2. Act
    const response = userResponseDto(user)

    // 3. Assert
    expect(response).toEqual({
      id: '123',
      first_name: 'john',
      last_name: 'doe',
      email: 'johndoe@email.com',
      phone_number: '1234567890'
    })
  })

  test('Correct request 3 - add password fields, hopefully they do not show up', () => {
    // 1. Arrange
    const user = {
      id: '123',
      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 response = userResponseDto(user)

    // 3. Assert
    expect(response).toEqual({
      id: '123',
      first_name: 'Yichen',
      last_name: 'Zhu',
      email: 'yichen@yichen.com',
      phone_number: '1234567890'
    })
  })
})

Last updated