Created
February 29, 2024 22:42
-
-
Save nullobject/84a80f20ca4909c5d4d1102e2ae2f304 to your computer and use it in GitHub Desktop.
Mock IntersectionObserver
This file contains 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 { act, render, screen } from "@testing-library/react" | |
import { List } from "./List" | |
type IntersectFn = (entries: any[]) => void | |
function mockIntersectionObserver(): [ | |
jest.MockedObject<IntersectionObserver>, | |
IntersectFn | |
] { | |
let intersectionObserverCallback: IntersectFn = () => {} | |
const intersect = (entries: any[]) => { | |
intersectionObserverCallback(entries) | |
} | |
const mock = { | |
root: null, | |
rootMargin: "", | |
thresholds: [0], | |
observe: jest.fn(), | |
unobserve: jest.fn(), | |
disconnect: jest.fn(), | |
takeRecords: jest.fn() | |
} | |
window.IntersectionObserver = jest.fn().mockImplementation(callback => { | |
intersectionObserverCallback = callback | |
return mock | |
}) | |
return [mock, intersect] | |
} | |
test("renders list items", async () => { | |
const handleFetch = jest.fn().mockResolvedValue([ | |
{ | |
id: "a", | |
text: "lorem" | |
}, | |
{ | |
id: "b", | |
text: "ipsum" | |
} | |
]) | |
const [, intersect] = mockIntersectionObserver() | |
render(<List onFetch={handleFetch} />) | |
expect(handleFetch).not.toHaveBeenCalled() | |
act(() => intersect([{ isIntersecting: true }])) | |
expect(handleFetch).toHaveBeenCalledTimes(1) | |
const items = await screen.findAllByRole("listitem") | |
expect(items).toHaveLength(2) | |
expect(items[0]).toHaveTextContent("lorem") | |
expect(items[1]).toHaveTextContent("ipsum") | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment