diff --git a/README.md b/README.md index ef3bc8f..aef9786 100644 --- a/README.md +++ b/README.md @@ -199,6 +199,32 @@ await selectEvent.clearAll(getByLabelText("Food")); expect(getByRole("form")).toHaveFormValues({ food: "" }); ``` +### `clearOne(input: HTMLElement, option: string | RegExp): Promise` + +Clear one selected value in the dropdown. + +```jsx +const { getByRole, getByLabelText } = render( +
+ + + +); +expect(getByRole("form")).toHaveFormValues({ + food: ["chocolate", "vanilla", "strawberry"], +}); +await selectEvent.clearOne(getByLabelText("Food"), "Vanilla"); +expect(getByRole("form")).toHaveFormValues({ + food: ["chocolate", "strawberry"], +}); +``` + ### `openMenu(input: HTMLElement): void` Opens the select dropdown menu by focusing the input and simulating a down arrow keypress. diff --git a/src/__tests__/select-event.test.tsx b/src/__tests__/select-event.test.tsx index bf9d78c..534397c 100644 --- a/src/__tests__/select-event.test.tsx +++ b/src/__tests__/select-event.test.tsx @@ -344,6 +344,25 @@ describe("The select event helpers", () => { expect(form).toHaveFormValues({ food: "vanilla" }); }); + it("clear one item in a multi-select dropdown", async () => { + const { form, input } = renderForm( + + ); + expect(form).toHaveFormValues({ + food: ["chocolate", "vanilla", "strawberry"], + }); + + await selectEvent.clearOne(input, "Vanilla"); + + expect(form).toHaveFormValues({ + food: ["chocolate", "strawberry"] + }); + }); + describe("when asynchronously generating the list of options", () => { // from https://github.com/JedWatson/react-select/blob/v3.0.0/docs/examples/CreatableAdvanced.js // mixed with Async Creatable Example from https://react-select.com/creatable diff --git a/src/index.ts b/src/index.ts index b365c20..21c08eb 100644 --- a/src/index.ts +++ b/src/index.ts @@ -158,5 +158,18 @@ export const clearAll = async (input: HTMLElement) => { await clear(input, clearAllButton); }; -const selectEvent = { select, create, clearFirst, clearAll, openMenu }; +/** + * Utility for clear one option, when has multiple options selected in a `react-select` dropdown. + * When find multiple options to remove it will remove the first occurrence + * @param {HTMLElement} input The input field (eg. `getByLabelText('The label')`) + * @param {String|RegExp} option The display name(s) for the option(s) to remove + */ + export const clearOne = async (input: HTMLElement, option: string | RegExp) => { + const container = getReactSelectContainerFromInput(input); + const options = await findAllByText(container, option); + const clearButton = options[0].parentNode?.querySelector('svg[aria-hidden="true"]')!; + await clear(input, clearButton); +}; + +const selectEvent = { select, create, clearFirst, clearAll, clearOne, openMenu }; export default selectEvent;