Skip to content

Commit

Permalink
unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
SKarolFolio committed Dec 20, 2024
1 parent 8318208 commit a489015
Show file tree
Hide file tree
Showing 3 changed files with 272 additions and 0 deletions.
54 changes: 54 additions & 0 deletions src/test/__tests__/common/helpers/complexLookup.helper.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
getLinkedField,
updateLinkedFieldValue,
getUpdatedSelectedEntries,
generateValidationRequestBody,
} from '@common/helpers/complexLookup.helper';
import * as ComplexLookupConstants from '@common/constants/complexLookup.constants';
import { AdvancedFieldType } from '@common/constants/uiControls.constants';
Expand Down Expand Up @@ -125,4 +126,57 @@ describe('complexLookup.helper', () => {
expect(result).toEqual(selectedEntries);
});
});

describe('generateValidationRequestBody', () => {
const mockMarcContent = {
field_1: 'value 1',
field_2: 'value 2',
};

const mockMarcData = {
parsedRecord: {
content: mockMarcContent,
},
} as unknown as MarcDTO;

it('returns empty object when marcData is null', () => {
const result = generateValidationRequestBody(null);

expect(result).toEqual({});
});

it('returns correct request body with default target', () => {
const result = generateValidationRequestBody(mockMarcData);

expect(result).toEqual({
rawMarc: JSON.stringify(mockMarcContent, null, 2),
target: 'CREATOR_OF_WORK',
});
});

it('returns correct request body with custom target', () => {
const customTarget = 'CUSTOM_TARGET';
const result = generateValidationRequestBody(mockMarcData, customTarget);

expect(result).toEqual({
rawMarc: JSON.stringify(mockMarcContent, null, 2),
target: customTarget,
});
});

it('returns correct request body with escaped content', () => {
const marcDataWithSpecialChars = {
parsedRecord: {
content: {
field: 'value\r\nwith\rlinebreaks',
},
},
} as unknown as MarcDTO;

const result = generateValidationRequestBody(marcDataWithSpecialChars);

expect(result.rawMarc).toContain('\\r');
expect(result.rawMarc).toContain('\\n');
});
});
});
153 changes: 153 additions & 0 deletions src/test/__tests__/common/hooks/useApi.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
import { act, renderHook } from '@testing-library/react';
import { setInitialGlobalState } from '@src/test/__mocks__/store';
import BaseApi from '@common/api/base.api';
import { UserNotificationFactory } from '@common/services/userNotification';
import { StatusType } from '@common/constants/status.constants';
import { useApi } from '@common/hooks/useApi';
import { useLoadingState, useStatusState } from '@src/store';

jest.mock('@common/api/base.api');
jest.mock('@common/services/userNotification', () => ({
UserNotificationFactory: {
createMessage: jest.fn(),
},
}));

describe('useApi', () => {
const mockSetIsLoading = jest.fn();
const mockAddStatusMessagesItem = jest.fn();
const mockResponse = { data: 'test data' };

beforeEach(() => {
setInitialGlobalState([
{
store: useLoadingState,
state: { setIsLoading: mockSetIsLoading },
},
{
store: useStatusState,
state: { addStatusMessagesItem: mockAddStatusMessagesItem },
},
]);

(BaseApi.getJson as jest.Mock).mockResolvedValue(mockResponse);
(BaseApi.generateUrl as jest.Mock).mockImplementation(url => url);
});

it('initializes with null data', () => {
const { result } = renderHook(() => useApi());

expect(result.current.data).toBeNull();
});

describe('makeRequest', () => {
it('handles successful GET request', async () => {
const { result } = renderHook(() => useApi());

await act(async () => {
await result.current.makeRequest({ url: '/test-url' });
});

expect(mockSetIsLoading).toHaveBeenCalledWith(true);
expect(BaseApi.getJson).toHaveBeenCalledWith({
url: '/test-url',
urlParams: undefined,
requestParams: {
method: 'GET',
headers: { 'content-type': 'application/json' },
},
});
expect(result.current.data).toEqual(mockResponse);
expect(mockSetIsLoading).toHaveBeenCalledWith(false);
});

it('handles POST request with body', async () => {
const { result } = renderHook(() => useApi());
const testBody = { key: 'value' };

await act(async () => {
await result.current.makeRequest({
url: '/test-url',
method: 'POST',
body: testBody,
});
});

expect(BaseApi.getJson).toHaveBeenCalledWith({
url: '/test-url',
urlParams: undefined,
requestParams: {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(testBody, null, 2),
},
});
});

it('handles URL parameters correctly', async () => {
const { result } = renderHook(() => useApi());
const urlParam = { name: 'id', value: '123' };

await act(async () => {
await result.current.makeRequest({
url: '/test-url',
urlParam,
});
});

expect(BaseApi.generateUrl).toHaveBeenCalledWith('/test-url', urlParam);
});

it('handles errors and shows notification', async () => {
const error = new Error('API Error');
(BaseApi.getJson as jest.Mock).mockRejectedValue(error);

const { result } = renderHook(() => useApi());

await act(async () => {
await result.current.makeRequest({ url: '/test-url' });
});

expect(UserNotificationFactory.createMessage).toHaveBeenCalledWith(StatusType.error, 'ld.errorMakingApiRequest');
expect(mockSetIsLoading).toHaveBeenCalledWith(false);
});

it('uses custom error message when provided', async () => {
const error = new Error('API Error');
(BaseApi.getJson as jest.Mock).mockRejectedValue(error);

const { result } = renderHook(() => useApi());

await act(async () => {
await result.current.makeRequest({
url: '/test-url',
errorMessageId: 'custom.error',
});
});

expect(UserNotificationFactory.createMessage).toHaveBeenCalledWith(StatusType.error, 'custom.error');
});

it('handles request params', async () => {
const { result } = renderHook(() => useApi());
const customRequestParams = { credentials: 'include' as RequestCredentials };

await act(async () => {
await result.current.makeRequest({
url: '/test-url',
requestParams: customRequestParams,
});
});

expect(BaseApi.getJson).toHaveBeenCalledWith({
url: '/test-url',
urlParams: undefined,
requestParams: {
method: 'GET',
headers: { 'content-type': 'application/json' },
...customRequestParams,
},
});
});
});
});
65 changes: 65 additions & 0 deletions src/test/__tests__/common/hooks/useComplexLookupValidation.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { renderHook } from '@testing-library/react';
import { setInitialGlobalState } from '@src/test/__mocks__/store';
import { useComplexLookupValidation } from '@src/common/hooks/useComplexLookupValidation';
import { useComplexLookupStore } from '@src/store/stores/complexLookup';

describe('useComplexLookupValidation', () => {
const mockAddAuthorityAssignmentCheckFailedIdsItem = jest.fn();
const mockResetAuthorityAssignmentCheckFailedIds = jest.fn();

beforeEach(() => {
setInitialGlobalState([
{
store: useComplexLookupStore,
state: {
authorityAssignmentCheckFailedIds: ['existing-id-1', 'existing-id-2'],
addAuthorityAssignmentCheckFailedIdsItem: mockAddAuthorityAssignmentCheckFailedIdsItem,
resetAuthorityAssignmentCheckFailedIds: mockResetAuthorityAssignmentCheckFailedIds,
},
},
]);
});

describe('addFailedEntryId', () => {
it('addAuthorityAssignmentCheckFailedIdsItem with provided id', () => {
const testId = 'test-id';

const { result } = renderHook(() => useComplexLookupValidation());
result.current.addFailedEntryId(testId);

expect(mockAddAuthorityAssignmentCheckFailedIdsItem).toHaveBeenCalledWith(testId);
});
});

describe('clearFailedEntryIds', () => {
it('calls resetAuthorityAssignmentCheckFailedIds', () => {
const { result } = renderHook(() => useComplexLookupValidation());
result.current.clearFailedEntryIds();

expect(mockResetAuthorityAssignmentCheckFailedIds).toHaveBeenCalled();
});
});

describe('checkFailedId', () => {
it('returns true for existing id', () => {
const { result } = renderHook(() => useComplexLookupValidation());
const exists = result.current.checkFailedId('existing-id-1');

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

it('returns false for non-existing id', () => {
const { result } = renderHook(() => useComplexLookupValidation());
const exists = result.current.checkFailedId('non-existing-id');

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

it('returns false for undefined id', () => {
const { result } = renderHook(() => useComplexLookupValidation());
const exists = result.current.checkFailedId();

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

0 comments on commit a489015

Please sign in to comment.