Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 27 additions & 4 deletions packages/ui/src/form/Checklist/Checklist.test.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,25 @@
import { Formik } from 'formik';
import { Formik, useFormikContext } from 'formik';
import React from 'react';

import { render, screen } from '@bigcommerce/checkout/test-utils';

import { Checklist } from './Checklist';

const renderChecklist = (children?: React.ReactNode) =>
const FormikValue = ({ name }: { name: string }) => {
const { values } = useFormikContext<Record<string, string>>();

return <span data-test="formik-value">{values[name]}</span>;
};

const renderChecklist = (children?: React.ReactNode, defaultSelectedItemId?: string) =>
render(
<Formik initialValues={{ payment: '' }} onSubmit={jest.fn()}>
<Checklist name="payment">{children}</Checklist>
<Formik initialValues={{ shippingOptionId: '' }} onSubmit={jest.fn()}>
<>
<Checklist defaultSelectedItemId={defaultSelectedItemId} name="shippingOptionId">
{children}
</Checklist>
<FormikValue name="shippingOptionId" />
</>
</Formik>,
);

Expand All @@ -27,4 +38,16 @@ describe('Checklist', () => {
expect(accordion).toHaveClass('form-checklist');
expect(accordion).toHaveClass('optimizedCheckout-form-checklist');
});

it('initializes the formik field with the default selected item id', () => {
renderChecklist(undefined, 'standard-shipping');

expect(screen.getByTestId('formik-value')).toHaveTextContent('standard-shipping');
});

it('leaves the formik field empty when no default selected item id is provided', () => {
renderChecklist();

expect(screen.getByTestId('formik-value')).toBeEmptyDOMElement();
});
});
6 changes: 6 additions & 0 deletions packages/ui/src/form/Checklist/Checklist.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,18 @@ export interface ChecklistContextProps {
export const ChecklistContext = createContext<ChecklistContextProps | undefined>(undefined);

export const Checklist: FunctionComponent<ChecklistProps> = ({
defaultSelectedItemId,
name,
onSelect = noop,
...props
}) => {
const { setFieldValue } = useFormikContext();

useEffect(() => {
if (defaultSelectedItemId) {
void setFieldValue(name, defaultSelectedItemId);
}
Comment thread
bc-maxy marked this conversation as resolved.

return () => {
void setFieldValue(name, '');
};
Expand All @@ -55,6 +60,7 @@ export const Checklist: FunctionComponent<ChecklistProps> = ({
<Accordion
{...props}
className="form-checklist optimizedCheckout-form-checklist"
defaultSelectedItemId={defaultSelectedItemId}
onSelect={handleSelect}
/>
</ChecklistContext.Provider>
Expand Down