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 = registerUserRequestDtoWe'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
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.
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.
Last updated