|
import { |
|
act, |
|
fireEvent, |
|
render, |
|
screen, |
|
waitFor, |
|
} from "@testing-library/react"; |
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; |
|
import Demo from "./Demo"; |
|
|
|
describe("App Component", () => { |
|
beforeEach(() => { |
|
const fetchMock = vi.fn(() => |
|
Promise.resolve({ |
|
json: () => |
|
Promise.resolve({ |
|
todos: [ |
|
{ |
|
userId: 1, |
|
id: 1, |
|
todo: "Sample Todo 1", |
|
completed: false, |
|
}, |
|
{ |
|
userId: 1, |
|
id: 2, |
|
todo: "Sample Todo 2", |
|
completed: true, |
|
}, |
|
{ |
|
userId: 1, |
|
id: 3, |
|
todo: "Sample Todo 3", |
|
completed: false, |
|
}, |
|
], |
|
}), |
|
}) |
|
); |
|
vi.stubGlobal("fetch", fetchMock); |
|
|
|
// Mock the IntersectionObserver |
|
const observeMock = vi.fn(); |
|
const unobserveMock = vi.fn(); |
|
const disconnectMock = vi.fn(); |
|
|
|
global.IntersectionObserver = vi.fn(function ( |
|
this: IntersectionObserver, |
|
callback |
|
) { |
|
(this as any).callback = callback; |
|
return { |
|
observe: observeMock, |
|
unobserve: unobserveMock, |
|
disconnect: disconnectMock, |
|
}; |
|
}) as unknown as typeof IntersectionObserver; |
|
}); |
|
|
|
afterEach(() => { |
|
// Restore the original implementations after each test |
|
vi.unstubAllGlobals(); |
|
}); |
|
|
|
it("renders the initial count and increments the count on button click", () => { |
|
render(<Demo />); |
|
const button = screen.getByRole("button", { name: /count is 0/i }); |
|
expect(button).toBeInTheDocument(); |
|
|
|
fireEvent.click(button); |
|
|
|
expect(button.textContent).toBe("count is 1"); |
|
}); |
|
|
|
it("fetches and displays the list of todos", async () => { |
|
render(<Demo />); |
|
|
|
// Wait for the todos to be rendered |
|
await waitFor(() => { |
|
expect(screen.getByText("Sample Todo 1")).toBeInTheDocument(); |
|
expect(screen.getByText("Sample Todo 2")).toBeInTheDocument(); |
|
expect(screen.getByText("Sample Todo 3")).toBeInTheDocument(); |
|
}); |
|
}); |
|
|
|
it("displays the correct number of todos", async () => { |
|
render(<Demo />); |
|
|
|
// Wait for the todos to be rendered |
|
await waitFor(() => { |
|
const todoItems = screen.getAllByRole("listitem"); |
|
expect(todoItems.length).toBe(3); |
|
}); |
|
}); |
|
|
|
it("should handle intersection observer correctly", () => { |
|
render(<Demo />); |
|
|
|
const observedDiv = screen.getByText("Out of view"); |
|
|
|
// Simulate the IntersectionObserver callback |
|
act(() => { |
|
const mockObserverInstance = (global.IntersectionObserver as any) |
|
.mock.instances[0]; |
|
mockObserverInstance.callback([{ isIntersecting: true }]); |
|
}); |
|
|
|
expect(observedDiv.textContent).toBe("In view"); |
|
}); |
|
}); |