Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve Search onChange signature #177

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
35 changes: 32 additions & 3 deletions src/components/Search/Search.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,25 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

import { describe, it, expect } from "vitest";
import { render } from "@testing-library/react";
import React from "react";
import { describe, it, expect, vi } from "vitest";
import { act, render, screen } from "@testing-library/react";
import React, { ChangeEvent } from "react";
import { userEvent } from "@storybook/test";

import { Search } from "./Search";
import { Form } from "@radix-ui/react-form";

type SearchTestProps = {
onChange?: (e: ChangeEvent) => void;
};

describe("Search", () => {
const SearchTest = (props: SearchTestProps) => (
<Form>
<Search name="search" onChange={props.onChange ?? (() => {})} />
</Form>
);

it("renders", () => {
const { asFragment } = render(
<Form>
Expand All @@ -30,4 +41,22 @@ describe("Search", () => {
);
expect(asFragment()).toMatchSnapshot();
});

it("calls onChange when text edited", async () => {
let value;
const onChange = vi
.fn()
.mockImplementation((e: ChangeEvent<HTMLInputElement>) => {
value = e.target.value;
});
render(<SearchTest onChange={onChange} />);
const query = "my query";
await act(async () => {
const input = screen.getByRole("searchbox");
await userEvent.type(input, query);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As far as I understand, the user-event library handles this so it doesn't need to be wrapped in an act(). At least, user-event's examples don't use act(): https://testing-library.com/docs/user-event/intro/#writing-tests-with-userevent

});

expect(onChange).toHaveBeenCalled();
expect(value).toEqual(query);
});
});
2 changes: 1 addition & 1 deletion src/components/Search/Search.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ type SearchProps = {
/**
* Event handler called when the search changes.
*/
onChange?: (e: React.ChangeEvent) => void;
onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
};

/**
Expand Down
Loading