suggestions.test.tsx 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { render, screen } from "@testing-library/react";
  2. import userEvent from "@testing-library/user-event";
  3. import { afterEach, describe, expect, it, vi } from "vitest";
  4. import { Suggestions } from "#/components/suggestions";
  5. describe("Suggestions", () => {
  6. const firstSuggestion = {
  7. label: "first-suggestion",
  8. value: "value-of-first-suggestion",
  9. };
  10. const secondSuggestion = {
  11. label: "second-suggestion",
  12. value: "value-of-second-suggestion",
  13. };
  14. const suggestions = [firstSuggestion, secondSuggestion];
  15. const onSuggestionClickMock = vi.fn();
  16. afterEach(() => {
  17. vi.clearAllMocks();
  18. });
  19. it("should render suggestions", () => {
  20. render(
  21. <Suggestions
  22. suggestions={suggestions}
  23. onSuggestionClick={onSuggestionClickMock}
  24. />,
  25. );
  26. expect(screen.getByTestId("suggestions")).toBeInTheDocument();
  27. const suggestionElements = screen.getAllByTestId("suggestion");
  28. expect(suggestionElements).toHaveLength(2);
  29. expect(suggestionElements[0]).toHaveTextContent("first-suggestion");
  30. expect(suggestionElements[1]).toHaveTextContent("second-suggestion");
  31. });
  32. it("should call onSuggestionClick when clicking a suggestion", async () => {
  33. const user = userEvent.setup();
  34. render(
  35. <Suggestions
  36. suggestions={suggestions}
  37. onSuggestionClick={onSuggestionClickMock}
  38. />,
  39. );
  40. const suggestionElements = screen.getAllByTestId("suggestion");
  41. await user.click(suggestionElements[0]);
  42. expect(onSuggestionClickMock).toHaveBeenCalledWith(
  43. "value-of-first-suggestion",
  44. );
  45. await user.click(suggestionElements[1]);
  46. expect(onSuggestionClickMock).toHaveBeenCalledWith(
  47. "value-of-second-suggestion",
  48. );
  49. });
  50. });