Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tests: adiciona testes #14

Merged
merged 4 commits into from
Dec 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 4 additions & 5 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
"vitest-sonar-reporter": "^2.0.0"
},
"devDependencies": {
"@testing-library/jest-dom": "^6.4.8",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/user-event": "^14.5.2",
"@types/react": "^18.2.66",
"@types/react-dom": "^18.2.22",
Expand Down
34 changes: 34 additions & 0 deletions src/Components/AdvantagesCard/index.test.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import "@testing-library/jest-dom";
import { render, screen, fireEvent } from "@testing-library/react";
import { describe, it, expect, vi } from "vitest";
import AdvantagesCard from "./index";

describe("AdvantagesCard", () => {
it("should render the title correctly", () => {
const mockTitle = "Benefícios exclusivos";

render(<AdvantagesCard title={mockTitle} onClick={() => {}} />);

const titleElement = screen.getByText(mockTitle);
expect(titleElement).toBeInTheDocument();
});

it("should call onClick when 'Saber mais' is clicked", () => {
const mockOnClick = vi.fn();
const mockTitle = "Benefícios exclusivos";

render(<AdvantagesCard title={mockTitle} onClick={mockOnClick} />);

const linkElement = screen.getByText("Saber mais");
fireEvent.click(linkElement);

expect(mockOnClick).toHaveBeenCalled();
});

it("should render without crashing when no props are provided", () => {
render(<AdvantagesCard />);
const linkElement = screen.getByText("Saber mais");

expect(linkElement).toBeInTheDocument();
});
});
72 changes: 72 additions & 0 deletions src/Components/AdvantagesModal/index.test.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import "@testing-library/jest-dom";
import { render, screen, fireEvent } from "@testing-library/react";
import { describe, it, expect, vi } from "vitest";
import AdvantagesModal from "./index";

describe("AdvantagesModal", () => {
const mockTitle = "Vantagens do Sindicato";
const mockDescription = "Este é o detalhamento das vantagens oferecidas.";
const mockOnClose = vi.fn();

it("should render the title correctly", () => {
render(
<AdvantagesModal
title={mockTitle}
description={mockDescription}
onClose={mockOnClose}
/>
);

const titleElement = screen.getByText(mockTitle);
expect(titleElement).toBeInTheDocument();
});

it("should render the description correctly", () => {
render(
<AdvantagesModal
title={mockTitle}
description={mockDescription}
onClose={mockOnClose}
/>
);

const descriptionElement = screen.getByText(mockDescription);
expect(descriptionElement).toBeInTheDocument();
});

it("should call onClose when the close button is clicked", () => {
render(
<AdvantagesModal
title={mockTitle}
description={mockDescription}
onClose={mockOnClose}
/>
);

const closeButton = screen.getByText("x");
fireEvent.click(closeButton);

expect(mockOnClose).toHaveBeenCalledTimes(1);
});

it("should render the contact information", () => {
render(
<AdvantagesModal
title={mockTitle}
description={mockDescription}
onClose={mockOnClose}
/>
);

const contactInfo = screen.getByText((content) =>
content.includes(
"Para mais informações, entre em contato com o Sindicato pelo número"
)
);

const phoneNumber = screen.getByText("(61) 3321-1949");

expect(contactInfo).toBeInTheDocument();
expect(phoneNumber).toBeInTheDocument();
});
});
50 changes: 50 additions & 0 deletions src/Pages/Public/ChangePasswordPage/index.test.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import "@testing-library/jest-dom";
import { render, screen, waitFor } from "@testing-library/react";
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import ChangePasswordPage from "./index";
import { MemoryRouter, Route, Routes } from "react-router-dom";
import { verifyToken } from "../../../Services/userService";

// Mock das funções do userService
vi.mock("../../../Services/userService", () => ({
verifyToken: vi.fn(),
changePasswordById: vi.fn(),
}));

describe("ChangePasswordPage", () => {
const renderComponent = (token) => {
render(
<MemoryRouter initialEntries={[`/change-password/${token}`]}>
<Routes>
<Route
path="/change-password/:token"
element={<ChangePasswordPage />}
/>
</Routes>
</MemoryRouter>
);
};

beforeEach(() => {
vi.clearAllMocks();
vi.spyOn(window, "alert").mockImplementation(() => {});
});

afterEach(() => {
window.alert.mockRestore();
});

it("should render the expired message when the token is invalid", async () => {
verifyToken.mockRejectedValueOnce(new Error("Token inválido"));

renderComponent("invalid-token");

await waitFor(() => {
expect(
screen.getByText("Essa página expirou ou não existe...")
).toBeInTheDocument();
});

expect(verifyToken).toHaveBeenCalledWith("invalid-token");
});
});
47 changes: 47 additions & 0 deletions src/Routes/index.test.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { render, screen } from "@testing-library/react";
import "@testing-library/jest-dom";
import { describe, it, expect, vi } from "vitest";
import Routes from "./index";
import { AuthProvider } from "../Context/auth";

vi.mock("./publicRoutes", () => ({
default: () => <div>Public Routes</div>,
}));

vi.mock("./protectedRoutes", () => ({
default: () => <div>Protected Routes</div>,
}));

describe("Routes Component", () => {
const renderWithAuth = (user) => {
if (user) {
localStorage.setItem("@App:user", JSON.stringify(user));
localStorage.setItem("@App:token", JSON.stringify("mockToken"));
} else {
localStorage.removeItem("@App:user");
localStorage.removeItem("@App:token");
}

return render(
<AuthProvider>
<Routes />
</AuthProvider>
);
};

it("should render only PublicRoutes when user is not signed in", () => {
renderWithAuth(null);

expect(screen.getByText("Public Routes")).toBeInTheDocument();
expect(screen.queryByText("Protected Routes")).not.toBeInTheDocument();
});

it("should render both ProtectedRoutes and PublicRoutes when user is signed in", () => {
const mockUser = { id: "123", name: "Test User" };

renderWithAuth(mockUser);

expect(screen.getByText("Protected Routes")).toBeInTheDocument();
expect(screen.getByText("Public Routes")).toBeInTheDocument();
});
});
87 changes: 87 additions & 0 deletions src/Routes/permissionProtect.test.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import "@testing-library/jest-dom";
import { render, screen, waitFor } from "@testing-library/react";
import { describe, it, expect, vi } from "vitest";
import PermissionProtect from "./permissionProtect";
import AuthContext from "../Context/auth";
import { getRoleById } from "../Services/RoleService/roleService";
import { checkAction } from "../Utils/permission";
import { MemoryRouter, Routes, Route } from "react-router-dom";

vi.mock("../Services/RoleService/roleService", () => ({
getRoleById: vi.fn(),
}));

vi.mock("../Utils/permission", () => ({
checkAction: vi.fn(),
}));

describe("PermissionProtect Component", () => {
const mockUser = {
id: "123",
role: "admin",
};

const renderComponent = (user, moduleName, actions) => {
return render(
<MemoryRouter initialEntries={["/"]}>
<AuthContext.Provider value={{ user }}>
<Routes>
<Route
path="/"
element={
<PermissionProtect
element={<div>Protected Content</div>}
moduleName={moduleName}
actions={actions}
/>
}
/>
<Route path="/unauthorized" element={<div>Unauthorized</div>} />
</Routes>
</AuthContext.Provider>
</MemoryRouter>
);
};

it("should render 'Loading...' while fetching permissions", () => {
getRoleById.mockResolvedValueOnce({ permissions: [] });

renderComponent(mockUser, "module1", ["read"]);

expect(screen.getByText("Loading...")).toBeInTheDocument();
});

it("should render the protected element when user has permission", async () => {
getRoleById.mockResolvedValueOnce({
permissions: [{ module: "module1", actions: ["read"] }],
});
checkAction.mockReturnValue(true);

renderComponent(mockUser, "module1", ["read"]);

await waitFor(() => {
expect(screen.getByText("Protected Content")).toBeInTheDocument();
});
});

it("should navigate to '/unauthorized' when user does not have permission", async () => {
getRoleById.mockResolvedValueOnce({
permissions: [{ module: "module1", actions: [] }],
});
checkAction.mockReturnValue(false);

renderComponent(mockUser, "module1", ["write"]);

await waitFor(() => {
expect(screen.getByText("Unauthorized")).toBeInTheDocument();
});
});

it("should navigate to '/unauthorized' when user role is not defined", async () => {
renderComponent({}, "module1", ["read"]);

await waitFor(() => {
expect(screen.getByText("Unauthorized")).toBeInTheDocument();
});
});
});
Loading
Loading