Skip to content

Commit

Permalink
Remove duplicate react-i18next mocks
Browse files Browse the repository at this point in the history
  • Loading branch information
mlqn committed Jun 6, 2024
1 parent d3067c6 commit 2e91dfa
Show file tree
Hide file tree
Showing 8 changed files with 64 additions and 136 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { ImageComponent } from './ImageComponent';
import { renderHookWithMockStore, renderWithMockStore } from '../../../../testing/mocks';
import { useLayoutSchemaQuery } from '../../../../hooks/queries/useLayoutSchemaQuery';
import { ComponentTypeV3 } from 'app-shared/types/ComponentTypeV3';
import { mockUseTranslation } from '@studio/testing/mocks/i18nMock';
import { mockUseTranslation, textMock } from '@studio/testing/mocks/i18nMock';

Check notice

Code scanning / CodeQL

Unused variable, import, function or class Note

Unused import mockUseTranslation.
import type { FormImageComponent } from '../../../../types/FormComponent';

const user = userEvent.setup();
Expand All @@ -22,15 +22,6 @@ const componentData: FormImageComponent = {
itemType: 'COMPONENT',
dataModelBindings: {},
};
const texts = {
'ux_editor.modal_properties_image_src_value_label': 'Source',
'ux_editor.modal_properties_image_placement_label': 'Placement',
'ux_editor.modal_properties_image_alt_text_label': 'Alt text',
'ux_editor.modal_properties_image_width_label': 'Width',
'ux_editor.modal_properties_image_placement_left': 'Left',
'ux_editor.modal_properties_image_placement_center': 'Center',
'ux_editor.modal_properties_image_placement_right': 'Right',
};

const waitForData = async () => {
const layoutSchemaResult = renderHookWithMockStore()(() => useLayoutSchemaQuery())
Expand All @@ -50,9 +41,6 @@ const render = async (props: Partial<IGenericEditComponent> = {}) => {
return renderWithMockStore()(<ImageComponent {...allProps} />);
};

// Mocks:
jest.mock('react-i18next', () => ({ useTranslation: () => mockUseTranslation(texts) }));

describe('ImageComponent', () => {
it('should call handleComponentUpdate callback with image src value for nb when image source input is changed', async () => {
const handleUpdate = jest.fn();
Expand Down Expand Up @@ -82,7 +70,7 @@ describe('ImageComponent', () => {
await render({ handleComponentChange: handleUpdate });

const widthInput = screen.getByRole('textbox', {
name: /width/i,
name: textMock('ux_editor.modal_properties_image_width_label'),
});

await user.type(widthInput, size);
Expand All @@ -105,7 +93,7 @@ describe('ImageComponent', () => {
});

await user.type(placementInput, 'L'); // Type something to trigger showing Select options
await user.click(screen.getByText('Left'));
await user.click(screen.getByText(textMock('ux_editor.modal_properties_image_placement_left')));

expect(handleUpdate).toHaveBeenCalledWith({
...componentData,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,9 @@ import { MapComponent } from './MapComponent';
import { renderWithMockStore, renderHookWithMockStore } from '../../../../testing/mocks';
import { appDataMock } from '../../../../testing/stateMocks';
import { useLayoutSchemaQuery } from '../../../../hooks/queries/useLayoutSchemaQuery';
import { mockUseTranslation } from '@studio/testing/mocks/i18nMock';
import { textMock } from '@studio/testing/mocks/i18nMock';
import type { IGenericEditComponent } from '../../componentConfig';

const texts: Record<string, string> = {
'validation_errors.required': 'Feltet er påkrevd!',
'validation_errors.numbers_only': 'Kun tall er gyldig verdi!',
'validation_errors.value_as_url': 'Ugyldig lenke!',
'ux_editor.center_location': 'Sentrum av kartet',
'ux_editor.map_layer': 'Kartlag',
'ux_editor.latitude_label': 'Latitude',
'ux_editor.longitude_label': 'Longitude',
'ux_editor.url_label': 'Lenke *',
'ux_editor.adjust_zoom': 'Standard zoom',
'ux_editor.add_map_layer': 'Legg til kartlag',
'ux_editor.attribution_label': 'Opphav',
'ux_editor.subdomains_label': 'Subdomener (kommaseparert)',
};

jest.mock('react-i18next', () => ({ useTranslation: () => mockUseTranslation(texts) }));
const handleComponentChangeMock = jest.fn();

const waitForData = async () => {
Expand All @@ -48,15 +32,15 @@ describe('MapComponent', () => {

test('should render titles', async () => {
await renderMapComponent({});
expect(screen.getByRole('heading', { level: 2, name: 'Sentrum av kartet' }));
expect(screen.getByRole('heading', { level: 2, name: 'Legg til kartlag' }));
expect(screen.getByRole('heading', { level: 2, name: textMock('ux_editor.center_location') }));
expect(screen.getByRole('heading', { level: 2, name: textMock('ux_editor.add_map_layer') }));
});

test('should render input-fields, latitude, longitude, zoom and button "Add map layer"', async () => {
await renderMapComponent({});
expect(screen.getByLabelText('Latitude')).toBeInTheDocument();
expect(screen.getByLabelText('Longitude')).toBeInTheDocument();
expect(screen.getByLabelText('Standard zoom')).toBeInTheDocument();
expect(screen.getByLabelText(textMock('ux_editor.latitude_label'))).toBeInTheDocument();
expect(screen.getByLabelText(textMock('ux_editor.longitude_label'))).toBeInTheDocument();
expect(screen.getByLabelText(textMock('ux_editor.adjust_zoom'))).toBeInTheDocument();
});

test('should be able to set latitude', async () => {
Expand All @@ -65,7 +49,7 @@ describe('MapComponent', () => {
handleComponentChange: handleComponentChangeMock,
});

const latitudeInput = screen.getByLabelText('Latitude');
const latitudeInput = screen.getByLabelText(textMock('ux_editor.latitude_label'));
await user.type(latitudeInput, '40');

expect(handleComponentChangeMock).toHaveBeenLastCalledWith({
Expand All @@ -79,7 +63,7 @@ describe('MapComponent', () => {
handleComponentChange: handleComponentChangeMock,
});

const longitudeInput = screen.getByLabelText('Longitude');
const longitudeInput = screen.getByLabelText(textMock('ux_editor.longitude_label'));
await user.type(longitudeInput, '21');

expect(handleComponentChangeMock).toHaveBeenLastCalledWith({
Expand All @@ -93,7 +77,7 @@ describe('MapComponent', () => {
handleComponentChange: handleComponentChangeMock,
});

const zoomInput = screen.getByLabelText('Standard zoom');
const zoomInput = screen.getByLabelText(textMock('ux_editor.adjust_zoom'));
await user.type(zoomInput, '2');

expect(handleComponentChangeMock).toHaveBeenLastCalledWith({ zoom: 2 });
Expand Down Expand Up @@ -127,16 +111,16 @@ describe('AddMapLayer', () => {
it('renders correctly when layers are not empty', async () => {
await renderMapComponent({ component: componentMock });

expect(screen.getByLabelText(texts['ux_editor.url_label'])).toBeInTheDocument();
expect(screen.getByLabelText(texts['ux_editor.attribution_label'])).toBeInTheDocument();
expect(screen.getByLabelText(texts['ux_editor.subdomains_label'])).toBeInTheDocument();
expect(screen.getByLabelText(textMock('ux_editor.url_label'))).toBeInTheDocument();
expect(screen.getByLabelText(textMock('ux_editor.attribution_label'))).toBeInTheDocument();
expect(screen.getByLabelText(textMock('ux_editor.subdomains_label'))).toBeInTheDocument();
});

test('should be able to set link', async () => {
const user = userEvent.setup();
await renderMapComponent({ component: componentMock });

const input = screen.getByLabelText(texts['ux_editor.url_label']);
const input = screen.getByLabelText(textMock('ux_editor.url_label'));
await user.type(input, 'test');

expect(handleComponentChangeMock).toHaveBeenLastCalledWith({
Expand All @@ -154,7 +138,7 @@ describe('AddMapLayer', () => {
const user = userEvent.setup();
await renderMapComponent({ component: componentMock });

const input = screen.getByLabelText(texts['ux_editor.attribution_label']);
const input = screen.getByLabelText(textMock('ux_editor.attribution_label'));
await user.type(input, 'test');

expect(handleComponentChangeMock).toHaveBeenLastCalledWith({
Expand All @@ -172,7 +156,7 @@ describe('AddMapLayer', () => {
const user = userEvent.setup();
await renderMapComponent({ component: componentMock });

const input = screen.getByLabelText(texts['ux_editor.subdomains_label']);
const input = screen.getByLabelText(textMock('ux_editor.subdomains_label'));
await user.type(input, 'test');

expect(handleComponentChangeMock).toHaveBeenLastCalledWith({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,9 @@ import { screen, waitFor } from '@testing-library/react';
import { EditStringValue } from './EditStringValue';
import { renderWithMockStore, renderHookWithMockStore } from '../../../testing/mocks';
import { useLayoutSchemaQuery } from '../../../hooks/queries/useLayoutSchemaQuery';
import { mockUseTranslation } from '@studio/testing/mocks/i18nMock';
import { ComponentTypeV3 } from 'app-shared/types/ComponentTypeV3';
import userEvent from '@testing-library/user-event';

jest.mock('react-i18next', () => ({
useTranslation: () => mockUseTranslation({}),
}));
import { textMock } from '@studio/testing/mocks/i18nMock';

const user = userEvent.setup();

Expand Down Expand Up @@ -49,7 +45,9 @@ describe('EditStringValue', () => {
it(' Ensure that the onChange handler is called with the correct arguments', async () => {
const handleComponentChange = jest.fn();
await render({ handleComponentChange });
const inputElement = screen.getByLabelText('maxLength');
const inputElement = screen.getByLabelText(
textMock('ux_editor.component_properties.maxLength'),
);
await user.type(inputElement, 'new value');
expect(handleComponentChange).toHaveBeenCalledWith({
id: 'c24d0812-0c34-4582-8f31-ff4ce9795e96',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,34 +1,26 @@
import type { KeyValuePairs } from 'app-shared/types/KeyValuePairs';
import { ComponentTypeV3 } from 'app-shared/types/ComponentTypeV3';
import { renderHook } from '@testing-library/react';
import { useComponentTypeName } from './useComponentTypeName';

// Test data:
const inputText = 'input';
const paragraphText = 'paragraph';
const texts: KeyValuePairs<string> = {
[`ux_editor.component_title.${ComponentTypeV3.Input}`]: inputText,
[`ux_editor.component_title.${ComponentTypeV3.Paragraph}`]: paragraphText,
};

// Mocks:
jest.mock('react-i18next', () => ({
...jest.requireActual('react-i18next'),
useTranslation: () => ({
t: (key: string) => texts?.[key] ?? key,
}),
}));
import { textMock } from '@studio/testing/mocks/i18nMock';

describe('useComponentTypeName', () => {
const { result } = renderHook(useComponentTypeName);

it('Returns the correct text if it exists', () => {
expect(result.current(ComponentTypeV3.Input)).toBe(inputText);
expect(result.current(ComponentTypeV3.Paragraph)).toBe(paragraphText);
expect(result.current(ComponentTypeV3.Input)).toBe(
textMock(`ux_editor.component_title.${ComponentTypeV3.Input}`),
);
expect(result.current(ComponentTypeV3.Paragraph)).toBe(
textMock(`ux_editor.component_title.${ComponentTypeV3.Paragraph}`),
);
});

it('Returns the component type if the text does not exist', () => {
expect(result.current(ComponentTypeV3.Header)).toBe(ComponentTypeV3.Header);
expect(result.current(ComponentTypeV3.Checkboxes)).toBe(ComponentTypeV3.Checkboxes);
expect(result.current(ComponentTypeV3.Header)).toBe(
textMock(`ux_editor.component_title.${ComponentTypeV3.Header}`),
);
expect(result.current(ComponentTypeV3.Checkboxes)).toBe(
textMock(`ux_editor.component_title.${ComponentTypeV3.Checkboxes}`),
);
});
});
13 changes: 4 additions & 9 deletions frontend/packages/ux-editor-v3/src/hooks/useText.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,17 @@ import { renderHookWithMockStore } from '../testing/mocks';
import { appDataMock } from '../testing/stateMocks';
import { useText } from './useText';
import type { IAppDataState } from '../features/appData/appDataReducers';
import { mockUseTranslation } from '@studio/testing/mocks/i18nMock';
import { textMock } from '@studio/testing/mocks/i18nMock';

// Test data:
const text = 'Lorem ipsum';
const textKey = 'test';
const notExistingKey = 'some-key';

// Mocks:
jest.mock('react-i18next', () => ({
useTranslation: () => mockUseTranslation({ [textKey]: text }),
}));

describe('useText', () => {
it('Returns text corresponding to given key', () => expect(renderAndRun(textKey)).toBe(text));
it('Returns text corresponding to given key', () =>
expect(renderAndRun(textKey)).toBe(textMock(textKey)));
it('Returns key if it is not present in the store', () =>
expect(renderAndRun(notExistingKey)).toBe(notExistingKey));
expect(renderAndRun(notExistingKey)).toBe(textMock(notExistingKey)));
});

const renderAndRun = (key: string) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,10 @@ import userEvent from '@testing-library/user-event';
import { MapComponent } from './MapComponent';
import { renderWithProviders, renderHookWithProviders } from '../../../../testing/mocks';
import { useLayoutSchemaQuery } from '../../../../hooks/queries/useLayoutSchemaQuery';
import { mockUseTranslation } from '@studio/testing/mocks/i18nMock';
import type { IGenericEditComponent } from '../../componentConfig';
import type { ComponentType } from 'app-shared/types/ComponentType';
import { textMock } from '@studio/testing/mocks/i18nMock';

const texts: Record<string, string> = {
'validation_errors.required': 'Feltet er påkrevd!',
'validation_errors.numbers_only': 'Kun tall er gyldig verdi!',
'validation_errors.value_as_url': 'Ugyldig lenke!',
'ux_editor.center_location': 'Sentrum av kartet',
'ux_editor.map_layer': 'Kartlag',
'ux_editor.latitude_label': 'Latitude',
'ux_editor.longitude_label': 'Longitude',
'ux_editor.url_label': 'Lenke *',
'ux_editor.adjust_zoom': 'Standard zoom',
'ux_editor.add_map_layer': 'Legg til kartlag',
'ux_editor.attribution_label': 'Opphav',
'ux_editor.subdomains_label': 'Subdomener (kommaseparert)',
};

jest.mock('react-i18next', () => ({ useTranslation: () => mockUseTranslation(texts) }));
const handleComponentChangeMock = jest.fn();

const waitForData = async () => {
Expand All @@ -48,7 +32,7 @@ describe('MapComponent', () => {
it('should render /Legg til kartlag/ button', async () => {
await renderMapComponent({});
expect(
screen.getByRole('button', { name: texts['ux_editor.add_map_layer'] }),
screen.getByRole('button', { name: textMock('ux_editor.add_map_layer') }),
).toBeInTheDocument();
});
});
Expand Down Expand Up @@ -80,16 +64,16 @@ describe('AddMapLayer', () => {
it('renders correctly when layers are not empty', async () => {
await renderMapComponent({ component: componentMock });

expect(screen.getByLabelText(texts['ux_editor.url_label'])).toBeInTheDocument();
expect(screen.getByLabelText(texts['ux_editor.attribution_label'])).toBeInTheDocument();
expect(screen.getByLabelText(texts['ux_editor.subdomains_label'])).toBeInTheDocument();
expect(screen.getByLabelText(textMock('ux_editor.url_label'))).toBeInTheDocument();
expect(screen.getByLabelText(textMock('ux_editor.attribution_label'))).toBeInTheDocument();
expect(screen.getByLabelText(textMock('ux_editor.subdomains_label'))).toBeInTheDocument();
});

test('should be able to set link', async () => {
const user = userEvent.setup();
await renderMapComponent({ component: componentMock });

const input = screen.getByLabelText(texts['ux_editor.url_label']);
const input = screen.getByLabelText(textMock('ux_editor.url_label'));
await user.type(input, 'test');

expect(handleComponentChangeMock).toHaveBeenLastCalledWith({
Expand All @@ -107,7 +91,7 @@ describe('AddMapLayer', () => {
const user = userEvent.setup();
await renderMapComponent({ component: componentMock });

const input = screen.getByLabelText(texts['ux_editor.attribution_label']);
const input = screen.getByLabelText(textMock('ux_editor.attribution_label'));
await user.type(input, 'test');

expect(handleComponentChangeMock).toHaveBeenLastCalledWith({
Expand All @@ -125,7 +109,7 @@ describe('AddMapLayer', () => {
const user = userEvent.setup();
await renderMapComponent({ component: componentMock });

const input = screen.getByLabelText(texts['ux_editor.subdomains_label']);
const input = screen.getByLabelText(textMock('ux_editor.subdomains_label'));
await user.type(input, 'test');

expect(handleComponentChangeMock).toHaveBeenLastCalledWith({
Expand Down
34 changes: 13 additions & 21 deletions frontend/packages/ux-editor/src/hooks/useComponentTypeName.test.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,26 @@
import type { KeyValuePairs } from 'app-shared/types/KeyValuePairs';
import { ComponentType } from 'app-shared/types/ComponentType';
import { renderHook } from '@testing-library/react';
import { useComponentTypeName } from './useComponentTypeName';

// Test data:
const inputText = 'input';
const paragraphText = 'paragraph';
const texts: KeyValuePairs<string> = {
[`ux_editor.component_title.${ComponentType.Input}`]: inputText,
[`ux_editor.component_title.${ComponentType.Paragraph}`]: paragraphText,
};

// Mocks:
jest.mock('react-i18next', () => ({
...jest.requireActual('react-i18next'),
useTranslation: () => ({
t: (key: string) => texts?.[key] ?? key,
}),
}));
import { textMock } from '@studio/testing/mocks/i18nMock';

describe('useComponentTypeName', () => {
const { result } = renderHook(useComponentTypeName);

it('Returns the correct text if it exists', () => {
expect(result.current(ComponentType.Input)).toBe(inputText);
expect(result.current(ComponentType.Paragraph)).toBe(paragraphText);
expect(result.current(ComponentType.Input)).toBe(
textMock(`ux_editor.component_title.${ComponentType.Input}`),
);
expect(result.current(ComponentType.Paragraph)).toBe(
textMock(`ux_editor.component_title.${ComponentType.Paragraph}`),
);
});

it('Returns the component type if the text does not exist', () => {
expect(result.current(ComponentType.Header)).toBe(ComponentType.Header);
expect(result.current(ComponentType.Checkboxes)).toBe(ComponentType.Checkboxes);
expect(result.current(ComponentType.Header)).toBe(
textMock(`ux_editor.component_title.${ComponentType.Header}`),
);
expect(result.current(ComponentType.Checkboxes)).toBe(
textMock(`ux_editor.component_title.${ComponentType.Checkboxes}`),
);
});
});
Loading

0 comments on commit 2e91dfa

Please sign in to comment.