Skip to content

Commit

Permalink
test: add unit test for new page components and other existing compon…
Browse files Browse the repository at this point in the history
…ents
  • Loading branch information
kristian4res committed Jun 30, 2024
1 parent a7eeb70 commit 1892be1
Show file tree
Hide file tree
Showing 12 changed files with 3,209 additions and 96 deletions.
8 changes: 4 additions & 4 deletions server/tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ describe("Test /api/roles GET endpoint", () => {
});
});

describe("Test /api/change_password/:user GET endpoint", () => {
describe("Test /api/change-password/:user GET endpoint", () => {
beforeEach(() => {
blaiseApiMock.reset();
});
Expand All @@ -206,7 +206,7 @@ describe("Test /api/change_password/:user GET endpoint", () => {
const password = "password-1234";
blaiseApiMock.setup((api) => api.changePassword(It.isAnyString(), It.isAnyString())).returns(_ => Promise.resolve(null));

const response = await sut.get("/api/change_password/"+username)
const response = await sut.get("/api/change-password/"+username)
.set("password", password);

expect(response.statusCode).toEqual(204);
Expand All @@ -217,7 +217,7 @@ describe("Test /api/change_password/:user GET endpoint", () => {
const username = "user1";
const password = "";

const response = await sut.get("/api/change_password/"+username)
const response = await sut.get("/api/change-password/"+username)
.set("password", password);

expect(response.statusCode).toEqual(400);
Expand All @@ -231,7 +231,7 @@ describe("Test /api/change_password/:user GET endpoint", () => {
blaiseApiMock.setup((a) => a.changePassword(It.isAnyString(), It.isAnyString()))
.returns(_ => Promise.reject(errorMessage));

const response = await sut.get("/api/change_password/"+username)
const response = await sut.get("/api/change-password/"+username)
.set("password", password);

expect(response.statusCode).toEqual(500);
Expand Down
96 changes: 96 additions & 0 deletions src/pages/users/UserProfileEdits/ChangePassword.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import React from "react";
import { render, cleanup } from "@testing-library/react";
import "@testing-library/jest-dom";
import ChangePassword from "./ChangePassword";
import { MemoryRouter } from "react-router-dom";
import userEvent from "@testing-library/user-event";
import { act } from "react-dom/test-utils";

jest.mock("blaise-login-react/blaise-login-react-client", () => ({
AuthManager: jest.fn().mockImplementation(() => ({
authHeader: () => ({
Authorization: "Bearer mockToken"
})
}))
}));

global.fetch = jest.fn(() =>
Promise.resolve({
status: 204,
json: () => Promise.resolve({ message: "Password changed successfully" })
})
) as jest.Mock;

const mockUserDetails = {
name: "testUser"
};

const mockState = {
pathname: `/users/${mockUserDetails.name}/change-password`,
state: { currentUser: "currentUser" }
};

beforeEach(() => {
(fetch as jest.Mock).mockClear();
});

afterEach(() => cleanup());

describe("ChangePassword Component", () => {
it("matches the snapshot", async () => {
const { asFragment } = render(
<MemoryRouter initialEntries={[mockState]}>
<ChangePassword />
</MemoryRouter>
);

expect(asFragment()).toMatchSnapshot();
});

it("displays error message when passwords do not match", async () => {
const { findByText, getByLabelText, getByText } = render(
<MemoryRouter initialEntries={[mockState]}>
<ChangePassword />
</MemoryRouter>
);

const newPasswordInput = getByLabelText("New password");
const confirmPasswordInput = getByLabelText("Confirm password");
const saveButton = getByText("Save");

act(() => {
userEvent.type(newPasswordInput, "password123");
userEvent.type(confirmPasswordInput, "password321");
userEvent.click(saveButton);
});

expect(await findByText(/Passwords do not match/i)).toBeVisible();
});

it.skip("calls fetch with correct parameters upon form submission with matching passwords", async () => {
const { getByLabelText, getByText, findByText } = render(
<MemoryRouter initialEntries={[mockState]}>
<ChangePassword />
</MemoryRouter>
);

const newPasswordInput = getByLabelText("New password");
const confirmPasswordInput = getByLabelText("Confirm password");
const saveButton = getByText("Save");

userEvent.type(newPasswordInput, "password123");
userEvent.type(confirmPasswordInput, "password123");
userEvent.click(saveButton);

expect(await findByText(/Passwords do not match/i)).not.toBeVisible();

// Improvement: Figure out why the fetch function is not being called
// expect(fetch).toHaveBeenCalledTimes(1);
// expect(fetch).toHaveBeenCalledWith("/api/change-password/testUser", {
// "headers": {
// "Authorization": "Bearer mockToken",
// "password": "password123"
// }
// });
});
});
100 changes: 100 additions & 0 deletions src/pages/users/UserProfileEdits/ChangeRole.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import React from "react";
import { render, cleanup, act } from "@testing-library/react";
import "@testing-library/jest-dom";
import ChangeRole from "./ChangeRole";
import { MemoryRouter, Route, Routes } from "react-router-dom";
import { getAllRoles, patchUserRolesAndPermissions } from "../../../api/http";
import { ValidUserRoles } from "../../../Interfaces";
import userEvent from "@testing-library/user-event";

jest.mock("../../../api/http", () => ({
getAllRoles: jest.fn(),
patchUserRolesAndPermissions: jest.fn()
}));

const mockRoles = [
{ name: ValidUserRoles.DST, description: "DST User" },
{ name: ValidUserRoles.BDSS, description: "BDSS User" },
{ name: ValidUserRoles.IPSFieldInterviewer, description: "IPS Field Interviewer User" },
{ name: ValidUserRoles.IPSManager, description: "IPS Manager User" },
{ name: ValidUserRoles.Editor, description: "Editor User" },
{ name: ValidUserRoles.EditorManager, description: "Editor Manager User" },
{ name: ValidUserRoles.TOAppointments, description: "TO Appointments User" },
{ name: ValidUserRoles.TOManager, description: "TO Manager User" },
{ name: ValidUserRoles.TOInterviewer, description: "TO Interviewer User" },
{ name: ValidUserRoles.SEL, description: "SEL User" },
{ name: ValidUserRoles.WelshSpeaker, description: "Welsh Speaker User" }
];
const mockUserDetails = {
data: { role: "DST" },
name: "testUser",
role: "DST",
serverParks: ["gusty"],
defaultServerPark: "gusty"
};

const mockState = {
pathname: `users/${mockUserDetails.name}/change-role`,
state: { currentUser: "currentUser", viewedUserDetails: mockUserDetails }
};

beforeEach(() => {
(getAllRoles as unknown as jest.Mock).mockResolvedValue([true, mockRoles]);
});

afterEach(() => cleanup());

describe("ChangeRole Component", () => {
it("matches the snapshot", async () => {
(patchUserRolesAndPermissions as unknown as jest.Mock).mockResolvedValue({ message: "Role updated successfully", status: 200 });

const { asFragment } = render(
<MemoryRouter initialEntries={[mockState]}>
<ChangeRole />
</MemoryRouter>
);

expect(asFragment()).toMatchSnapshot();
});

it("renders and displays the correct initial role", async () => {
(patchUserRolesAndPermissions as unknown as jest.Mock).mockResolvedValue({ message: "Role updated successfully", status: 200 });

const { findByText, findAllByText } = render(
<MemoryRouter initialEntries={[mockState]}>
<ChangeRole />
</MemoryRouter>
);

expect(await findByText(/Current role:/i)).toBeVisible();
expect((await findAllByText(/DST/i))[0]).toBeVisible();
});

it("updates role upon form submission", async () => {
(patchUserRolesAndPermissions as unknown as jest.Mock).mockResolvedValue({ message: "Role updated successfully", status: 200 });
global.confirm = jest.fn(() => true);

const { findByText, findByRole } = render(
<MemoryRouter initialEntries={[mockState]}>
<ChangeRole />
</MemoryRouter>
);

const select = await findByRole("combobox");
const saveButton = await findByText("Save");

act(() => {
userEvent.selectOptions(select, ["IPS Field Interviewer"]);
});

expect(await findByText(/IPS Field Interviewer/i)).toBeVisible();

act(() => {
userEvent.click(saveButton);
});
expect(patchUserRolesAndPermissions).toHaveBeenCalledTimes(1);

// Improvement: Ensure the user from the pathname is extracted and used to call the function
// expect(patchUserRolesAndPermissions).toHaveBeenCalledWith("testUser", "IPS Field Interviewer", ["gusty"], "gusty");
});
});
75 changes: 75 additions & 0 deletions src/pages/users/UserProfileEdits/ProfileTable.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import React from "react";
import "@testing-library/jest-dom";
import { render, screen } from "@testing-library/react";
import { BrowserRouter as Router } from "react-router-dom";
import ProfileTable from "./ProfileTable";

const currentUser = {
name: "CurrentUser",
role: "DST",
defaultServerPark: "gusty",
serverParks: ["gusty"]
};

const viewedUserDetails = {
data: {
name: "John Doe",
role: "IPS Manager",
defaultServerPark: "gusty",
serverParks: ["gusty", "cma"]
},
status: 200,
message: "Successfully fetched user details for John Doe"
};

describe("ProfileTable", () => {
it("matches snapshot", () => {
const { asFragment } = render(
<Router>
<ProfileTable currentUser={currentUser} viewedUserDetails={viewedUserDetails} />
</Router>
);

expect(asFragment()).toMatchSnapshot();
});

it("renders user details correctly", async () => {
render(
<Router>
<ProfileTable currentUser={currentUser} viewedUserDetails={viewedUserDetails} />
</Router>
);

expect(screen.getByText("John Doe")).toBeVisible();
expect(screen.getByText("IPS Manager")).toBeVisible();
expect(screen.getByText("gusty")).toBeVisible();
expect(screen.getByText("gusty, cma")).toBeVisible();

expect(await screen.findByText("Delete")).toBeVisible();
const changeButtons = await screen.findAllByText("Change");
changeButtons.forEach(button => {
expect(button).toBeVisible();
});
});

it("displays \"Not found\" for missing user details", () => {
const missingDetails = {
data: {
name: "",
role: "",
defaultServerPark: "",
serverParks: []
},
status: 500,
message: "User not found"
};

render(
<Router>
<ProfileTable currentUser={currentUser} viewedUserDetails={missingDetails} />
</Router>
);

expect(screen.getAllByText("Not found").length).toBeGreaterThan(0);
});
});
Loading

0 comments on commit 1892be1

Please sign in to comment.