-
-
Save Jasper-Nelligan/52de80834a727e9beb7c358ac010ef50 to your computer and use it in GitHub Desktop.
Testing a Shadcn Select component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { render, fireEvent, waitFor } from "@testing-library/react"; | |
import { describe, it, expect, vi, beforeEach } from 'vitest'; | |
import '@testing-library/jest-dom'; | |
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "./ui/select"; | |
function SelectExample() { | |
return ( | |
<Select> | |
<SelectTrigger data-testid="select-element"> | |
<SelectValue /> | |
</SelectTrigger> | |
<SelectContent> | |
<SelectGroup> | |
<SelectItem value={"Red"}>{"Red"}</SelectItem> | |
<SelectItem value={"Blue"}>{"Blue"}</SelectItem> | |
<SelectItem value={"Green"}>{"Green"}</SelectItem> | |
</SelectGroup> | |
</SelectContent> | |
</Select> | |
) | |
} | |
// required to open Shadcn Select component | |
export class MockPointerEvent extends Event { | |
button: number; | |
ctrlKey: boolean; | |
constructor(type, props) { | |
super(type, props); | |
if (props.button != null) { | |
this.button = props.button; | |
} | |
if (props.ctrlKey != null) { | |
this.ctrlKey = props.ctrlKey; | |
} | |
} | |
} | |
window.PointerEvent = MockPointerEvent as any; | |
window.HTMLElement.prototype.scrollIntoView = vi.fn(); | |
window.HTMLElement.prototype.hasPointerCapture = vi.fn(); | |
window.HTMLElement.prototype.releasePointerCapture = vi.fn(); | |
describe("SelectTest", () => { | |
beforeEach(() => { | |
vi.clearAllMocks(); | |
}); | |
it("Select renders options correctly", async () => { | |
const { findByText, findByTestId, queryByText } = render(<SelectExample />); | |
await waitFor(() => { | |
expect(queryByText("Green")).not.toBeInTheDocument(); | |
}); | |
const selectElement = await findByTestId("select-element"); | |
fireEvent.pointerDown( | |
selectElement, | |
new MockPointerEvent('pointerdown', { | |
ctrlKey: false, | |
button: 0, | |
}) | |
); | |
waitFor(() => { | |
expect(findByText("Green")).toBeInTheDocument(); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment