Skip to content

Commit

Permalink
fix(test): fixed unit test cases
Browse files Browse the repository at this point in the history
  • Loading branch information
abhi-markan committed Jul 30, 2024
1 parent d93a9da commit be87d57
Show file tree
Hide file tree
Showing 10 changed files with 296 additions and 234 deletions.
398 changes: 199 additions & 199 deletions package-lock.json

Large diffs are not rendered by default.

8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,10 @@
"@types/lodash": "^4.17.7",
"@types/node": "^20.14.13",
"@types/supertest": "^6.0.2",
"@typescript-eslint/eslint-plugin": "^7.17.0",
"@typescript-eslint/parser": "^7.17.0",
"@typescript-eslint/eslint-plugin": "^7.18.0",
"@typescript-eslint/parser": "^7.18.0",
"chance": "^1.1.12",
"cspell": "^8.12.1",
"cspell": "^8.13.0",
"eslint": "8.57.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-config-airbnb-typescript": "^18.0.0",
Expand All @@ -99,7 +99,7 @@
"eslint-plugin-simple-import-sort": "^12.1.1",
"eslint-plugin-switch-case": "^1.1.2",
"eslint-plugin-unused-imports": "^4.0.1",
"husky": "^9.1.3",
"husky": "^9.1.4",
"jest": "29.7.0",
"jest-when": "^3.6.0",
"lint-staged": "^15.2.7",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ describe('CompaniesHouseService', () => {
await expect(getCompanyPromise).rejects.toHaveProperty('innerError', axiosError);
});

it(`throws a CompaniesHouseNotFoundException when the Companies House API returns a 404 response containing the error string 'company-profile-not-found'`, async () => {
it(`throws a CompaniesHouseNotFoundException when the Companies House API returns a 404 response status'`, async () => {
const axiosError = new AxiosError();
axiosError.response = {
data: getCompanyCompaniesHouseNotFoundResponse,
Expand Down
4 changes: 2 additions & 2 deletions src/helper-modules/companies-house/known-errors.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { HttpStatus } from '@nestjs/common';
import { messageCheck, statusCheck } from '@ukef/helpers/response-status';
import { messageCheck, statusCheck } from '@ukef/helpers/response-status.helper';
import { AxiosError } from 'axios';

import { CompaniesHouseInvalidAuthorizationException } from './exception/companies-house-invalid-authorization.exception';
Expand All @@ -11,7 +11,7 @@ export type KnownErrors = KnownError[];
type KnownError = { checkHasError: (error: Error) => boolean; throwError: (error: AxiosError) => never };

export const getCompanyMalformedAuthorizationHeaderKnownCompaniesHouseError = (): KnownError => ({
checkHasError: (error) => statusCheck({ error, status: HttpStatus.UNAUTHORIZED }) && messageCheck({ error, search: 'Invalid Authorization header' }),
checkHasError: (error) => statusCheck({ error, status: HttpStatus.BAD_REQUEST }) && messageCheck({ error, search: 'Invalid Authorization header' }),
throwError: (error) => {
throw new CompaniesHouseMalformedAuthorizationHeaderException(
`Invalid 'Authorization' header. Check that your 'Authorization' header is well-formed.`,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,25 @@ type CompaniesHouseHttpErrorCallback = (error: Error) => ObservableInput<never>;
export const createWrapCompaniesHouseHttpGetErrorCallback =
({ messageForUnknownError, knownErrors }: { messageForUnknownError: string; knownErrors: KnownErrors }): CompaniesHouseHttpErrorCallback =>
(error: Error) => {
if (error instanceof AxiosError && error.response && typeof error.response.data === 'object') {
const errorResponseData = error.response.data;
let errorMessage: string;
if (error instanceof AxiosError) {
let message: string;
const status: number = error?.response?.status;

if (typeof errorResponseData.error === 'string') {
errorMessage = errorResponseData.error;
} else if (errorResponseData.errors && errorResponseData.errors[0] && typeof errorResponseData.errors[0].error === 'string') {
errorMessage = errorResponseData.errors[0].error;
if (typeof error?.response?.data?.error === 'string') {
message = error.response.data.error;
} else if (error?.response?.data?.errors[0] && typeof error?.response?.data?.errors[0]?.error === 'string') {
message = error.response.data.errors[0].error;
}

if (errorMessage) {
const errorMessageInLowerCase = errorMessage.toLowerCase();

knownErrors.forEach(({ caseInsensitiveSubstringToFind, throwError }) => {
if (errorMessageInLowerCase.includes(caseInsensitiveSubstringToFind.toLowerCase())) {
/**
* CH API will throw empty response body with `404`
* upon sending a valid non-existent 8 digit CRN.
*
* Otherwise `404` with an expected response body.
*/
if (message || status) {
knownErrors.forEach(({ checkHasError, throwError }) => {
if (checkHasError(error)) {
return throwError(error);
}
});
Expand Down
2 changes: 1 addition & 1 deletion src/helpers/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export * from './regex.helper';
export * from './response-status';
export * from './response-status.helper';
export * from './transform-interceptor.helper';
66 changes: 66 additions & 0 deletions src/helpers/response-status.helper.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { HttpStatus } from '@nestjs/common';
import { isAxiosError } from 'axios';

import { statusCheck } from './response-status.helper';

jest.mock('axios', () => ({
isAxiosError: jest.fn(),
}));

describe('statusCheck', () => {
beforeEach(() => {
(isAxiosError as unknown as jest.Mock).mockReturnValue(true);
});

it('should return true when isAxiosError is true and status matches', () => {
const error = {
response: {
status: HttpStatus.BAD_REQUEST,
},
name: 'Bad request',
message: 'Bad request',
} as Error;

const result = statusCheck({ error, status: HttpStatus.BAD_REQUEST });

expect(result).toBe(true);
});

it('should return false when isAxiosError is true but status does not match', () => {
const error = {
response: {
status: HttpStatus.BAD_REQUEST,
},
name: 'Bad request',
message: 'Bad request',
} as Error;

const result = statusCheck({ error, status: HttpStatus.NOT_FOUND });

expect(result).toBe(false);
});

it('should return false when isAxiosError is false', () => {
const error = {
response: {
status: HttpStatus.BAD_REQUEST,
},
name: 'Bad request',
message: 'Bad request',
} as Error;

(isAxiosError as unknown as jest.Mock).mockReturnValue(false);

const result = statusCheck({ error, status: HttpStatus.BAD_REQUEST });

expect(result).toBe(false);
});

it('should return false when error does not have a response', () => {
const error = {} as Error;

const result = statusCheck({ error, status: HttpStatus.BAD_REQUEST });

expect(result).toBe(false);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@ export const statusCheck = ({ error, status }: { error: Error; status: HttpStatu
*/
export const messageCheck = ({ error, search }: { error: Error; search: string }): boolean => {
if (!isAxiosError(error) || !error?.response?.data) {
return;
return false;
}

let message: string;

if (error?.response?.data?.errors?.length && typeof error?.response?.data?.errors[0]?.error === 'string') {
if (typeof error?.response?.data?.error === 'string') {
message = error.response.data.error;
} else if (error?.response?.data?.errors[0] && typeof error?.response?.data?.errors[0]?.error === 'string') {
message = error.response.data.errors[0].error;
}

Expand Down
7 changes: 2 additions & 5 deletions test/companies/get-company-by-registration-number.api-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,16 +97,13 @@ describe('GET /companies?registrationNumber=', () => {
},
);

it(`returns a 404 response if the Companies House API returns a 404 response containing the error string 'company-profile-not-found'`, async () => {
it(`returns a 404 response if the Companies House API returns a 404 response status code`, async () => {
requestToGetCompanyByRegistrationNumber(companiesHousePath).reply(404, getCompanyCompaniesHouseNotFoundResponse);

const { status, body } = await api.get(mdmPath);

expect(status).toBe(404);
expect(body).toStrictEqual({
statusCode: 404,
message: 'Not found',
});
expect(body).toStrictEqual({});
});

it('returns a 422 response if the Companies House API returns an overseas company', async () => {
Expand Down
9 changes: 1 addition & 8 deletions test/support/generator/get-company-generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,14 +185,7 @@ export class GetCompanyGenerator extends AbstractGenerator<CompanyValues, Genera
type: 'ch:service',
};

const getCompanyCompaniesHouseNotFoundResponse: GetCompanyCompaniesHouseMultipleErrorResponse = {
errors: [
{
error: 'company-profile-not-found',
type: 'ch:service',
},
],
};
const getCompanyCompaniesHouseNotFoundResponse: GetCompanyCompaniesHouseMultipleErrorResponse = undefined;

return {
companiesHousePath,
Expand Down

0 comments on commit be87d57

Please sign in to comment.