Skip to content

Commit

Permalink
Replace remaining enzyme tests with working tests
Browse files Browse the repository at this point in the history
  • Loading branch information
asanchezr committed Oct 26, 2023
1 parent 78ebb49 commit 285eedd
Show file tree
Hide file tree
Showing 3 changed files with 208 additions and 75 deletions.
6 changes: 3 additions & 3 deletions source/frontend/src/AppRouter.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { lookupCodesSlice } from './store/slices/lookupCodes';
import { networkSlice } from './store/slices/network/networkSlice';
import { tenantsSlice } from './store/slices/tenants';
import { defaultTenant } from './tenants/config/defaultTenant';
import { mockKeycloak, render, RenderOptions, screen } from './utils/test-utils';
import { cleanup, mockKeycloak, render, RenderOptions, screen } from './utils/test-utils';

const history = createMemoryHistory();
const storeState = {
Expand Down Expand Up @@ -61,11 +61,11 @@ jest.mock('@/store/slices/tenants/useTenants', () => ({
jest.mock('./hooks/pims-api/useApiUsers');
(useApiUsers as jest.MockedFunction<typeof useApiUsers>).mockReturnValue({
activateUser: jest.fn(),
exportUsers: jest.fn(),
getUser: jest.fn().mockResolvedValue(getUserMock()),
getUserInfo: jest.fn().mockResolvedValue(getUserMock()),
getUsersPaged: jest.fn(),
putUser: jest.fn(),
exportUsers: jest.fn(),
});

describe('PSP routing', () => {
Expand All @@ -86,7 +86,7 @@ describe('PSP routing', () => {
};

afterEach(() => {
// cleanup();
cleanup();
jest.clearAllMocks();
});

Expand Down
225 changes: 153 additions & 72 deletions source/frontend/src/components/common/form/Select.test.tsx
Original file line number Diff line number Diff line change
@@ -1,73 +1,154 @@
// import React from 'react';

// import { PropertyClassificationTypes } from '@/constants/propertyClassificationTypes';
// import { getIn, useFormikContext } from 'formik';
// import renderer from 'react-test-renderer';

// import { FastSelect } from './FastSelect';

// jest.mock('formik');

// (useFormikContext as jest.Mock).mockReturnValue({
// values: {
// classificationId: PropertyClassificationTypes.CoreOperational,
// classification: 'zero',
// },
// registerField: jest.fn(),
// unregisterField: jest.fn(),
// });
// (getIn as jest.Mock).mockReturnValue(0);

// const options = [
// {
// label: 'zero',
// value: '0',
// selected: true,
// },
// {
// label: 'one',
// value: '1',
// selected: true,
// },
// {
// label: 'two',
// value: '2',
// selected: true,
// },
// ];

describe('LimitedSelect - Enzyme Tests - NEEDS REFACTORING', () => {
it('should be implemented', async () => {});
// it('limited fast select renders correctly', () => {
// const context = useFormikContext();
// const tree = renderer
// .create(
// <FastSelect
// limitLabels={['one']}
// formikProps={context}
// type="number"
// options={options}
// field={'TestField'}
// />,
// )
// .toJSON();
// expect(tree).toMatchSnapshot();
// });
//
// it('only renders the limited options + the previous value', async () => {
// const context = useFormikContext();
// const component = mount(
// <FastSelect
// limitLabels={['one']}
// formikProps={context}
// type="number"
// options={options}
// field={'TestField'}
// />,
// );
// expect(component.find('option')).toHaveLength(2);
// });
});
import { Formik, FormikProps } from 'formik';
import React from 'react';

import { act, fireEvent, render, RenderOptions, screen, userEvent } from '@/utils/test-utils';

import { Select, SelectOption, SelectProps } from './Select';

const countries: SelectOption[] = [
{ label: 'Austria', value: 'AT' },
{ label: 'United States', value: 'US' },
{ label: 'Ireland', value: 'IE' },
];

const onSubmit = jest.fn();

describe('Select component', () => {
const setup = (
options: RenderOptions & { props?: Partial<SelectProps> } & {
initialValues?: { countryId: string };
} = {},
) => {
const formikRef = React.createRef<FormikProps<any>>();
const utils = render(
<Formik
innerRef={formikRef}
initialValues={options?.initialValues ?? { countryId: '' }}
onSubmit={onSubmit}
>
<Select
field="countryId"
label="Test Dropdown"
options={countries}
placeholder={options?.props?.placeholder ?? 'Select a country'}
{...(options?.props ?? {})}
/>
</Formik>,
{ ...options },
);

return {
...utils,
getFormikRef: () => formikRef,
};
};

beforeEach(() => {});

afterEach(() => {
jest.clearAllMocks();
});

it('renders as expected', () => {
const { asFragment } = setup();
expect(asFragment()).toMatchSnapshot();
});

it('should correctly set default option', () => {
setup();
const option: HTMLOptionElement = screen.getByRole('option', { name: 'Select a country' });
expect(option.selected).toBe(true);
});

it('should display the correct number of options', () => {
setup();
expect(screen.getAllByRole('option').length).toBe(4);
});

it('should not render default option if placeholder property is undefined', () => {
setup({ props: { placeholder: undefined } });
expect(screen.getAllByRole('option').length).toBe(3);
});

// TODO: Remove this line when unit tests above are fixed
export {};
it('allows the user to change selected value and calls onChange callback', async () => {
const onChange = jest.fn();
setup({ props: { onChange } });

await act(async () =>
userEvent.selectOptions(
screen.getByRole('combobox'),
screen.getByRole('option', { name: 'Ireland' }),
),
);

const option: HTMLOptionElement = screen.getByRole('option', { name: 'Ireland' });
expect(option.selected).toBe(true);
expect(onChange).toHaveBeenCalled();
});

it('supports disabled property as intended', () => {
setup({ props: { disabled: true } });
const select = screen.getByRole('combobox');
expect(select).toHaveAttribute('disabled');
});

it('shows a tooltip as intended', () => {
setup({ props: { tooltip: 'test tooltip' } });
expect(document.querySelector('svg[class="tooltip-icon"]')).toBeInTheDocument();
});

it('should handle numeric values', () => {
const numericOptions = countries.map((opt, i) => {
opt.value = i;
return opt;
});
setup({ props: { type: 'number', options: numericOptions } });
expect(screen.getAllByRole('option').length).toBe(4);
});

it('should set numeric value in formik', async () => {
const numericOptions = countries.map((opt, i) => {
opt.value = i;
return opt;
});
const { getFormikRef } = setup({ props: { type: 'number', options: numericOptions } });
const formik = getFormikRef();

// select a value and trigger a blur event on the select
await act(async () =>
userEvent.selectOptions(
screen.getByRole('combobox'),
screen.getByRole('option', { name: 'Ireland' }),
),
);
await act(async () => fireEvent.blur(screen.getByRole('combobox')));

expect(formik.current?.values.countryId).toBe(2);
});

it('should set numeric value to undefined in formik when default option is selected', async () => {
const numericOptions = countries.map((opt, i) => {
opt.value = i;
return opt;
});
const { getFormikRef } = setup({ props: { type: 'number', options: numericOptions } });
const formik = getFormikRef();

// select a value and trigger a blur event on the select
await act(async () =>
userEvent.selectOptions(
screen.getByRole('combobox'),
screen.getByRole('option', { name: 'Ireland' }),
),
);
await act(async () =>
userEvent.selectOptions(
screen.getByRole('combobox'),
screen.getByRole('option', { name: 'Select a country' }),
),
);
await act(async () => fireEvent.blur(screen.getByRole('combobox')));

expect(formik.current?.values.countryId).toBeUndefined();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Select component renders as expected 1`] = `
<DocumentFragment>
<div
class="Toastify"
/>
<div />
<div
class="form-group"
>
<label
class="form-label"
for="input-countryId"
>
Test Dropdown
</label>
<select
class="form-select form-control"
id="input-countryId"
name="countryId"
>
<option
value=""
>
Select a country
</option>
<option
class="option"
data-testid="select-option-AT"
value="AT"
>
Austria
</option>
<option
class="option"
data-testid="select-option-US"
value="US"
>
United States
</option>
<option
class="option"
data-testid="select-option-IE"
value="IE"
>
Ireland
</option>
</select>
</div>
</DocumentFragment>
`;

0 comments on commit 285eedd

Please sign in to comment.