Skip to content

Commit

Permalink
fix(AutoComplete): fix autocomplete not working
Browse files Browse the repository at this point in the history
  • Loading branch information
SevenOutman committed Apr 30, 2022
1 parent 4ae9880 commit a58f1ea
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/AutoComplete.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ export function AutoComplete({
<RsAutoComplete
{...field}
onChange={(newValue, event) => {
field.onChange(event);
// Can't use field.onChange here because event can be other types than ChangeEvent
// e.g. MouseEvent from clicking suggested value options
// KeyboardEvent from selecting suggested value options with Enter
form.setFieldValue(field.name, newValue);
onChange?.(newValue, event);
}}
{...props}
Expand Down
67 changes: 67 additions & 0 deletions src/__tests__/AutoComplete.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import React from "react";

import { render, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { Formik, Form, Field, FormikProps } from "formik";
import _ from "lodash";

import { AutoComplete } from "../AutoComplete";

test("Works with formik", async () => {
const formikRef = React.createRef<FormikProps<any>>();
const { getByTestId } = render(
<Formik
innerRef={formikRef}
initialValues={{
text: "value",
}}
onSubmit={_.noop}
>
<Form>
<Field name="text" component={AutoComplete} data-testid="input" />
</Form>
</Formik>
);

expect(getByTestId("input")).toHaveValue("value");

userEvent.clear(getByTestId("input"));
userEvent.type(getByTestId("input"), "newvalue");

await waitFor(() => {
expect(formikRef.current?.values).toHaveProperty("text", "newvalue");
});
});

test("Autocomplete shouold work", async () => {
const formikRef = React.createRef<FormikProps<any>>();
const { getByTestId, getByText } = render(
<Formik
innerRef={formikRef}
initialValues={{
text: "",
}}
onSubmit={_.noop}
>
<Form>
<Field
name="text"
component={AutoComplete}
data={["suggested result"]}
data-testid="input"
/>
</Form>
</Formik>
);

userEvent.type(getByTestId("input"), "s");

userEvent.click(getByText("suggested result"));

await waitFor(() => {
expect(formikRef.current?.values).toHaveProperty(
"text",
"suggested result"
);
});
});

0 comments on commit a58f1ea

Please sign in to comment.