front/__tests__/SignIn.test.jsx
2024-10-19 10:57:44 +03:00

53 lines
2.0 KiB
JavaScript

import React from "react";
import { render, screen, fireEvent } from "@testing-library/react";
import SignIn from "src/pages/SignIn";
import { displayMessage } from "src/backend/notifications/notifications";
import { post } from "src/backend/api";
// Mock the displayMessage and post functions
jest.mock("src/backend/notifications/notifications", () => ({
displayMessage: jest.fn(),
}));
jest.mock("src/backend/api", () => ({
post: jest.fn(),
}));
describe("SignIn Page", () => {
beforeEach(() => {
jest.clearAllMocks();
});
test("renders SignIn form", () => {
render(<SignIn />);
expect(screen.getByLabelText(/username/i)).toBeInTheDocument();
expect(screen.getByLabelText(/password/i)).toBeInTheDocument();
expect(screen.getByText(/sign in/i)).toBeInTheDocument();
});
test("displays error message on failed login", async () => {
post.mockResolvedValueOnce({ ok: false, data: { message: "Invalid credentials" } });
render(<SignIn />);
fireEvent.change(screen.getByLabelText(/username/i), { target: { value: "user" } });
fireEvent.change(screen.getByLabelText(/password/i), { target: { value: "password" } });
fireEvent.click(screen.getByText(/sign in/i));
expect(await screen.findByText(/invalid credentials/i)).toBeInTheDocument();
expect(displayMessage).toHaveBeenCalledWith("Invalid credentials", "error");
});
test("displays additional info message after multiple login attempts", async () => {
post.mockResolvedValueOnce({ ok: false, data: { message: "Invalid credentials" } });
render(<SignIn />);
fireEvent.change(screen.getByLabelText(/username/i), { target: { value: "user" } });
fireEvent.change(screen.getByLabelText(/password/i), { target: { value: "password" } });
// Simulate two failed login attempts
fireEvent.click(screen.getByText(/sign in/i));
fireEvent.click(screen.getByText(/sign in/i));
expect(displayMessage).toHaveBeenCalledWith("Note that you need to enter your ID name", "info");
});
});