|
12 | 12 | * */ |
13 | 13 |
|
14 | 14 | import React from "react"; |
15 | | -import { render, screen } from "@testing-library/react"; |
| 15 | +import { render, screen, act } from "@testing-library/react"; |
16 | 16 | import userEvent from "@testing-library/user-event"; |
17 | 17 | import "@testing-library/jest-dom"; |
18 | 18 | import SearchInput from "../search-input"; |
| 19 | +import { DEBOUNCE_WAIT } from "../../../utils/constants"; |
19 | 20 |
|
20 | 21 | describe("SearchInput", () => { |
21 | 22 | test("renders with custom placeholder", () => { |
@@ -58,4 +59,39 @@ describe("SearchInput", () => { |
58 | 59 | rerender(<SearchInput term="new" onSearch={jest.fn()} />); |
59 | 60 | expect(screen.getByDisplayValue("new")).toBeInTheDocument(); |
60 | 61 | }); |
| 62 | + |
| 63 | + describe("debounced prop", () => { |
| 64 | + beforeEach(() => jest.useFakeTimers()); |
| 65 | + afterEach(() => jest.useRealTimers()); |
| 66 | + |
| 67 | + test("calls onSearch after debounce delay when debounced is true", async () => { |
| 68 | + const onSearch = jest.fn(); |
| 69 | + const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime }); |
| 70 | + render(<SearchInput term="" onSearch={onSearch} debounced />); |
| 71 | + const input = screen.getByPlaceholderText("Search..."); |
| 72 | + await user.type(input, "something"); |
| 73 | + expect(onSearch).not.toHaveBeenCalled(); |
| 74 | + act(() => jest.advanceTimersByTime(DEBOUNCE_WAIT)); |
| 75 | + expect(onSearch).toHaveBeenCalledWith("something"); |
| 76 | + }); |
| 77 | + |
| 78 | + test("does not call onSearch on Enter when debounced is true", async () => { |
| 79 | + const onSearch = jest.fn(); |
| 80 | + const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime }); |
| 81 | + render(<SearchInput term="" onSearch={onSearch} debounced />); |
| 82 | + const input = screen.getByPlaceholderText("Search..."); |
| 83 | + await user.type(input, "something{Enter}"); |
| 84 | + expect(onSearch).not.toHaveBeenCalled(); |
| 85 | + }); |
| 86 | + |
| 87 | + test("does not call onSearch on typing without Enter when not debounced", async () => { |
| 88 | + const onSearch = jest.fn(); |
| 89 | + const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime }); |
| 90 | + render(<SearchInput term="" onSearch={onSearch} />); |
| 91 | + const input = screen.getByPlaceholderText("Search..."); |
| 92 | + await user.type(input, "something"); |
| 93 | + act(() => jest.runAllTimers()); |
| 94 | + expect(onSearch).not.toHaveBeenCalled(); |
| 95 | + }); |
| 96 | + }); |
61 | 97 | }); |
0 commit comments