Skip to content

Commit

Permalink
test(ModalContent): mock useModal, add tests for content scrolled logic
Browse files Browse the repository at this point in the history
  • Loading branch information
YossiSaadi committed Oct 6, 2024
1 parent 4f74817 commit b11a9fc
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -1,10 +1,28 @@
import React from "react";
import { render } from "@testing-library/react";
import { render, fireEvent } from "@testing-library/react";
import ModalContent from "../ModalContent";
import { useModal } from "../../context/ModalContext";

jest.mock("../../context/ModalContext", () => ({
useModal: jest.fn()
}));
const useModalMocked = jest.mocked(useModal);

describe("ModalContent", () => {
const childrenContent = <span>My content</span>;

const useModalMockedReturnedValue = {
modalId: "modal-id",
setTitleId: jest.fn(),
setDescriptionId: jest.fn(),
contentScrolled: false,
setContentScrolled: jest.fn()
};

beforeEach(() => {
useModalMocked.mockReturnValue(useModalMockedReturnedValue);
});

it("renders the children correctly", () => {
const { getByText } = render(<ModalContent>{childrenContent}</ModalContent>);
expect(getByText("My content")).toBeInTheDocument();
Expand All @@ -14,4 +32,42 @@ describe("ModalContent", () => {
const { container } = render(<ModalContent />);
expect(container.firstChild).toBeInTheDocument();
});

it("calls setContentScrolled with 'true' when scrolled down", () => {
const { getByTestId } = render(
<ModalContent id="modal-content" data-testid="modal-content">
{childrenContent}
</ModalContent>
);

const contentDiv = getByTestId("modal-content");
fireEvent.scroll(contentDiv, { target: { scrollTop: 100 } });

expect(useModalMockedReturnedValue.setContentScrolled).toHaveBeenCalledWith(true);
});

it("calls setContentScrolled with 'false' when scrolled to the top", () => {
const { getByTestId } = render(
<ModalContent id="modal-content" data-testid="modal-content">
{childrenContent}
</ModalContent>
);

const contentDiv = getByTestId("modal-content");

fireEvent.scroll(contentDiv, { target: { scrollTop: 100 } });
fireEvent.scroll(contentDiv, { target: { scrollTop: 0 } });

expect(useModalMockedReturnedValue.setContentScrolled).toHaveBeenLastCalledWith(false);
});

it("does not call setContentScrolled if no scroll occurs", () => {
render(
<ModalContent id="modal-content" data-testid="modal-content">
{childrenContent}
</ModalContent>
);

expect(useModalMockedReturnedValue.setContentScrolled).not.toHaveBeenCalled();
});
});
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React from "react";

export interface ModalContextProps extends ModalProviderValue {
contentScrolled?: boolean;
contentScrolled: boolean;
setContentScrolled: (scrolled: boolean) => void;
}

Expand Down

0 comments on commit b11a9fc

Please sign in to comment.