Skip to content

Commit

Permalink
feat: add unit tests for utils. refactoring and fixing issues with as…
Browse files Browse the repository at this point in the history
…ync on funcitons in utils folder. resolving issue with app missing a package that was included in the sourcecode. refined README
  • Loading branch information
daniel78uk committed Dec 1, 2023
1 parent 08cec8e commit 48f7b3e
Show file tree
Hide file tree
Showing 10 changed files with 269 additions and 110 deletions.
16 changes: 8 additions & 8 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -2,30 +2,30 @@ SERVICE_NAME=smart-incident-reporting
VERSION=$(shell git rev-parse --short HEAD)
NODE_VERSION=$(cat .nvmrc)

.PHONY: install start backend-up backend-down build-image
.PHONY: install start backend-up backend-down build-image install-nodejs-version use-nodejs-version

APPS=nvm

all: install

install:
brew install ${APPS}
NVM_DIR="$${HOME}/.nvm" && . "$${NVM_DIR}/nvm.sh" && nvm install ${NODE_VERSION}
NVM_DIR="$${HOME}/.nvm" && . "$${NVM_DIR}/nvm.sh" && nvm use ${NODE_VERSION}
npm i
npm rebuild node-sass
npm rebuild node-sass # this is needed if it runs in osx since sass is a very old lib it needs rebuiling
npm run build

install-nodejs-version:
NVM_DIR="$${HOME}/.nvm" && . "$${NVM_DIR}/nvm.sh" && nvm install ${NODE_VERSION}

use-nodejs-version:
NVM_DIR="$${HOME}/.nvm" && . "$${NVM_DIR}/nvm.sh" && nvm use ${NODE_VERSION}

start:
$(MAKE) backend-up

npm run build
npm run dev

restart:
kill -9 $(lsof -t -i:8000)
npm run dev

build-image:
docker build -t $(SERVICE_NAME):latest .
docker tag $(SERVICE_NAME):latest \
Expand Down
9 changes: 0 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,6 @@ To start the application `dev` environment please run:
$ make start
```

and:

```sh
$ make restart
```

In case you want to restart the `dev` environment.


# Testing Docker build of the image

To test the creation on the Docker image please run:
Expand Down
13 changes: 12 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@
"moment-timezone": "^0.5.43",
"node-fetch": "^2.6.7",
"node-sass": "^9.0.0",
"nunjucks": "^3.2.4"
"nunjucks": "^3.2.4",
"postcode-validator": "^3.8.20"
},
"devDependencies": {
"concurrently": "^8.2.2",
Expand Down Expand Up @@ -92,4 +93,4 @@
],
"delay": 3000
}
}
}
2 changes: 1 addition & 1 deletion server/services/redis.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ const set = async (request, key, value) => {

const deleteItem = async (request, key) => {
const client = getRedisClient(request)
const keyWithSessionId = `${getSessionKey(request)}.${key}`//?
const keyWithSessionId = `${getSessionKey(request)}.${key}` //?

try {
await client.del(keyWithSessionId)
Expand Down
42 changes: 20 additions & 22 deletions server/utils/util.js
Original file line number Diff line number Diff line change
@@ -1,35 +1,33 @@

const wreck = require('@hapi/wreck').defaults({
timeout: 10000
})

function request (method, url, options, ext = false) {
return wreck[method](url, options)
.then(response => {
const res = response.res
const payload = response.payload
const makeRequest = async (method, url, options, ext = false) => {
try {
const response = await wreck[method](url, options)
const { res, payload } = response

if (res.statusCode !== 200) {
const err = (payload || new Error('Unknown error'))
throw err
}
if (res.statusCode !== 200) {
const err = payload || new Error('Unknown error')
throw err
}

return payload
})
}
function get (url, options, ext = false) {
return request('get', url, options, ext)
return payload
} catch (error) {
throw error
}
}

function post (url, options) {
return request('post', url, options)
}
function getJson (url, ext = false) {
return get(url, { json: true }, ext)
}
const get = async (url, options, ext = false) =>
makeRequest('get', url, options, ext)

const post = async (url, options) => makeRequest('post', url, options)

const getJson = async (url, ext = false) => get(url, { json: true }, ext)

module.exports = {
get,
post,
getJson,
request
makeRequest
}
81 changes: 21 additions & 60 deletions server/utils/validation.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,40 +4,17 @@ const { postcodeValidator } = require('postcode-validator')

const VALIDATION_SUMMARY_HEADING = 'There is a problem'

/**
* Performs validation, checks an email address using a regular expresssion to determine whether or not it is valid
* i.e. in a correct email format.
* @param {*} value The email address to validate.
* @returns True if the email address is valid, otherwise false.
*/
const email = value => {
return value.match(
const email = (value) =>
value.match(
/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/
)
}

/**
* Performs validation, checks whether or not the incoming value is empty.
* @param {*} value The value to be validated.
* @returns True if the value is empty, otherwise false.
*/
const empty = value => !value || value.toString().trim().length === 0
const empty = (value) => !value || value.toString().trim().length === 0

/**
* Performs validation, checks whether or not the incoming value exceeds the maximum allowed length.
* @param {*} value The value to be validated.
* @param {*} characterLimit The maximum allowed number of characters.
* @returns True if the value is too long, otherwise false.
*/
const maxLength = (value, characterLimit) =>
value && value.toString().trim().length > characterLimit

/**
* Performs validation, checks whether or not the incoming value is a valid UK postcode.
* @param {*} value The value to be validated.
* @returns True if the value is a postcode, otherwise false.
*/
const postcode = value =>
const postcode = (value) =>
!value || postcodeValidator(value.toString().trim(), 'GB')

const Validators = {
Expand All @@ -47,47 +24,31 @@ const Validators = {
postcode
}

/**
* Creates an error summary object for use in form-layout pages that
* include field validation
* @param {*} errors An array of errors
* @returns An error summary object
*/
const buildErrorSummary = errors => {
return errors && errors.length
const buildErrorSummary = (errors) =>
errors && errors.length
? {
errorSummary: {
titleText: VALIDATION_SUMMARY_HEADING,
errorList: _getErrorList(errors)
errorList: errors.map(({ name, text }) => ({
text,
href: `#${name}`
}))
},
fieldErrors: _getFieldErrors(errors)
fieldErrors: errors.reduce(
(fieldErrors, { name, text }) => ({
...fieldErrors,
[name]: { text }
}),
{}
)
}
: {}
}

const _getErrorList = errors => {
let errorList = []
if (errors && Array.isArray(errors) && errors.length) {
errorList = errors.map(error => {
return {
text: error.text,
href: `#${error.name}`
}
})
}

return errorList
}

const _getFieldErrors = errors => {
const fieldErrors = {}
for (const { name, text } of errors) {
fieldErrors[name] = { text }
}
return fieldErrors
}

module.exports = {
email,
empty,
maxLength,
postcode,
buildErrorSummary,
Validators
}
14 changes: 7 additions & 7 deletions test/unit/services/redis.service.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ describe('RedisService', () => {
tempKeys = []
})

describe('get()', () => {
describe('get', () => {
it('should get value from Redis', async () => {
await mockClient.setex(mockTestKey, mockTTLValue, mockValue)

Expand All @@ -67,7 +67,7 @@ describe('RedisService', () => {
})
})

describe('set()', () => {
describe('set', () => {
it('should set value in Redis', async () => {
await set(mockRequest, 'testKey', mockValue)

Expand All @@ -77,8 +77,8 @@ describe('RedisService', () => {
})
})

describe('delete()', () => {
it.only('should delete value from Redis', async () => {
describe('delete', () => {
it('should delete value from Redis', async () => {
await mockClient.setex(mockTestKey, mockTTLValue, mockValue)

await deleteItem(mockRequest, 'testKey')
Expand All @@ -89,7 +89,7 @@ describe('RedisService', () => {
})
})

describe('deleteSessionData()', () => {
describe('deleteSessionData', () => {
it('should delete all session data from Redis', async () => {
await mockClient.setex(`${mockTestKey}1`, mockTTLValue, mockValue)
await mockClient.setex(`${mockTestKey}2`, mockTTLValue, mockValue)
Expand All @@ -104,7 +104,7 @@ describe('RedisService', () => {
})
})

describe('isJsonString()', () => {
describe('isJsonString', () => {
it('should correctly identify JSON strings', () => {
expect(isJsonString('{"key": "value"}')).toBe(true)
expect(isJsonString('["value1", "value2"]')).toBe(true)
Expand All @@ -114,7 +114,7 @@ describe('RedisService', () => {
})
})

describe('isBooleanString()', () => {
describe('isBooleanString', () => {
it('should correctly identify boolean strings', () => {
expect(isBooleanString('true')).toBe(true)
expect(isBooleanString('false')).toBe(true)
Expand Down
Loading

0 comments on commit 48f7b3e

Please sign in to comment.