Skip to content

Commit

Permalink
implements Pedro's tests
Browse files Browse the repository at this point in the history
  • Loading branch information
pedroalonsoms committed Jun 13, 2024
1 parent c4912e3 commit bd4b69a
Show file tree
Hide file tree
Showing 5 changed files with 293 additions and 0 deletions.
26 changes: 26 additions & 0 deletions cypress/e2e/searchbar.cy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
describe("Searchbar", () => {
beforeEach(() => {
cy.visit("/login");
cy.get("label").contains("Email").click().type("[email protected]");
cy.get("label").contains("Password").click().type("cypress");
cy.get("button").contains("Log in").click();
cy.wait(10000);
});
it("Expands searchbar", () => {
cy.get('[data-testid="search-box"]').should("have.class", "w-10");
cy.get('[data-testid="search-icon"]').click();
cy.get('[data-testid="search-box"]').should("have.class", "w-64");
});

// Pedro Alonso Moreno A01174050 - Test #1/1
it("Searches for a user", () => {
cy.get('[data-testid="search-icon"]').click();
const comboboxInput = cy.get('[data-testid="combobox-input"]');
comboboxInput.should("have.focus");
comboboxInput.type("cypress");
cy.wait(8000);
cy.get('[data-testid="option-cypress prueba"]').should("exist");
cy.get('[data-testid="option-cypress prueba"]').click();
cy.url().should("include", "/profile");
});
});
47 changes: 47 additions & 0 deletions test/DragUser.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import DraggableUser from "@/components/modals/DraggableUser";
import { screen, within } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { customDndProvider } from "./mock-utils/mockUtils";

const users = [
{
userId: "1",
name: "Test User",
photoUrl: "https://test.com",
},
{
userId: "2",
name: "Test User 2",
photoUrl: "https://test.com",
},
{
userId: "3",
name: "Test User 3",
photoUrl: "https://test.com",
},
];

vi.mock("react", () => {
return {
useState: vi.fn(() => [false, vi.fn()]),
useEffect: vi.fn(),
};
});

describe("Should render SprintSurveyStepTwo", () => {
// Pedro Alonso Moreno Salcedo A01741437 - Test #9/10
it("Should render dragUser", () => {
customDndProvider(<DraggableUser user={users[0]} times={2} />, vi.fn());
const draggableUser = screen.getByTestId("draggable-1");

Check failure on line 35 in test/DragUser.test.tsx

View workflow job for this annotation

GitHub Actions / unit-test

test/DragUser.test.tsx > Should render SprintSurveyStepTwo > Should render dragUser

TestingLibraryElementError: Unable to find an element by: [data-testid="draggable-1"] Ignored nodes: comments, script, style <body> <div> <div aria-describedby="DndDescribedBy-0" aria-disabled="false" aria-roledescription="draggable" role="button" tabindex="0" > <div class="group relative flex max-w-max flex-col items-center justify-center" > <span class="relative left-3 top-3 z-10 flex h-3 w-3 cursor-move items-center justify-center rounded-full bg-primary-light p-2 text-[0.6rem] font-medium text-white" > x 2 </span> <div class="undefined bg-white group h-fit w-fit rounded-full p-1 drop-shadow-lg focus-within:outline-primary focus:outline-primary" > <img alt="User profile photo" class="rounded-full h-10 w-10" data-nimg="1" decoding="async" height="300" loading="lazy" src="/_next/image?url=https%3A%2F%2Ftest.com&w=640&q=75" srcset="/_next/image?url=https%3A%2F%2Ftest.com&w=384&q=75 1x, /_next/image?url=https%3A%2F%2Ftest.com&w=640&q=75 2x" style="color: transparent;" width="300" /> </div> <div class="absolute bottom-7 left-1/2 z-10 ml-auto mr-auto min-w-max -translate-x-1/2 rotate-180 scale-0 transform rounded-xl px-3 py-2 text-xs font-medium transition-all duration-500 group-hover:scale-100" > <div class="flex max-w-xs flex-col items-center shadow-lg" > <div class="clip-bottom h-2 w-4 bg-primary/90" /> <div class="w-[25ch] rotate-180 cursor-default rounded bg-primary/90 p-2 text-center text-xs text-white" > Test User </div> </div> </div> </div> </div> <div id="DndDescribedBy-0" style="display: none;" > To pick up a draggable item, press the space bar. While dragging, use the arrow keys to move the item. Press space again to drop the item in its new position, or press escape to cancel. </div> <div aria-atomic="true" aria-live="assertive" id="DndLiveRegion-0" role="status" style="position: fixed; width: 1px; height: 1px; margin: -1px; border: 0px; padding: 0px; overflow: hidden; clip-path: inset(100%); white-space: nowrap;" /> </div> </body> ❯ Object.getElementError node_modules/@testing-library/dom/dist/config.js:37:19 ❯ node_modules/@testing-library/dom/dist/query-helpers.js:76:38 ❯ node_modules/@testing-library/dom/dist/query-helpers.js:52:17 ❯ node_modules/@testing-library/dom/dist/query-helpers.js:95:19 ❯ test/DragUser.test.tsx:35:34
expect(draggableUser).toBeInTheDocument();
});

// Pedro Alonso Moreno Salcedo A01741437 - Test #10/10
it("Should not render dragUser", () => {
customDndProvider(<DraggableUser user={users[0]} />, vi.fn());
const draggableUser = screen.getByTestId(`draggable-${users[0].userId}`);

Check failure on line 42 in test/DragUser.test.tsx

View workflow job for this annotation

GitHub Actions / unit-test

test/DragUser.test.tsx > Should render SprintSurveyStepTwo > Should not render dragUser

TestingLibraryElementError: Unable to find an element by: [data-testid="draggable-1"] Ignored nodes: comments, script, style <body> <div> <div aria-describedby="DndDescribedBy-1" aria-disabled="false" aria-roledescription="draggable" role="button" tabindex="0" > <div class="group relative flex max-w-max flex-col items-center justify-center" > <div class="undefined bg-white group h-fit w-fit rounded-full p-1 drop-shadow-lg focus-within:outline-primary focus:outline-primary" > <img alt="User profile photo" class="rounded-full h-10 w-10" data-nimg="1" decoding="async" height="300" loading="lazy" src="/_next/image?url=https%3A%2F%2Ftest.com&w=640&q=75" srcset="/_next/image?url=https%3A%2F%2Ftest.com&w=384&q=75 1x, /_next/image?url=https%3A%2F%2Ftest.com&w=640&q=75 2x" style="color: transparent;" width="300" /> </div> <div class="absolute bottom-7 left-1/2 z-10 ml-auto mr-auto min-w-max -translate-x-1/2 rotate-180 scale-0 transform rounded-xl px-3 py-2 text-xs font-medium transition-all duration-500 group-hover:scale-100" > <div class="flex max-w-xs flex-col items-center shadow-lg" > <div class="clip-bottom h-2 w-4 bg-primary/90" /> <div class="w-[25ch] rotate-180 cursor-default rounded bg-primary/90 p-2 text-center text-xs text-white" > Test User </div> </div> </div> </div> </div> <div id="DndDescribedBy-1" style="display: none;" > To pick up a draggable item, press the space bar. While dragging, use the arrow keys to move the item. Press space again to drop the item in its new position, or press escape to cancel. </div> <div aria-atomic="true" aria-live="assertive" id="DndLiveRegion-1" role="status" style="position: fixed; width: 1px; height: 1px; margin: -1px; border: 0px; padding: 0px; overflow: hidden; clip-path: inset(100%); white-space: nowrap;" /> </div> </body> ❯ Object.getElementError node_modules/@testing-library/dom/dist/config.js:37:19 ❯ node_modules/@testing-library/dom/dist/query-helpers.js:76:38 ❯ node_modules/@testing-library/dom/dist/query-helpers.js:52:17 ❯ node_modules/@testing-library/dom/dist/query-helpers.js:95:19 ❯ test/DragUser.test.tsx:42:34
expect(
within(draggableUser).queryByTestId(`user-${users[0].userId}-times`),
).not.toBeInTheDocument();
});
});
119 changes: 119 additions & 0 deletions test/RulerStepOne.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import RulerStepOne from "@/components/modals/ruler/RulerStepOne";
import { Emotion, RulerSurveyAnswer } from "@/types/types";
import { fireEvent, render, screen } from "@testing-library/react";
import { Mock, describe, expect, it, vi } from "vitest";

const randomEmotion = {
row: Math.floor(Math.random() * 12),
col: Math.floor(Math.random() * 12),
};

const emotionBgColor = (emotion: Emotion) => {
if (emotion.pleasantness < 0 && emotion.energy < 0) return "bg-blue-400";
else if (emotion.pleasantness < 0 && emotion.energy > 0) return "bg-red-400";
else if (emotion.pleasantness > 0 && emotion.energy < 0)
return "bg-green-400";
else return "bg-yellow-400";
};

let setMockEmotion: Mock, nextStepMock: Mock, rulerEmotion: RulerSurveyAnswer;

describe("RulerSurvey Component Test", () => {
beforeEach(() => {
setMockEmotion = vi.fn();
nextStepMock = vi.fn();
rulerEmotion = {
userId: "prueba",
emotion: {
name: "",
pleasantness: 2,
description: "",
energy: 2,
id: 1,
},
comment: "",
};
});

// Pedro Alonso Moreno Salcedo A01741437 - Test #1/10
it("Should render step one", () => {
render(
<RulerStepOne
setEmotion={setMockEmotion}
rulerSurveyAnswer={rulerEmotion}
nextStep={nextStepMock}
/>,
);

expect(screen.getByTestId("ruler-step-one")).toBeInTheDocument();
});

// Pedro Alonso Moreno Salcedo A01741437 - Test #2/10
it("Should get an emotion", () => {
render(
<RulerStepOne
setEmotion={setMockEmotion}
rulerSurveyAnswer={rulerEmotion}
nextStep={nextStepMock}
/>,
);

const emotion = screen.getByTestId(
`emotion-${randomEmotion.row}-${randomEmotion.col}`,
);
fireEvent.mouseEnter(emotion);
expect(emotion).toHaveClass("scale-150");
fireEvent.mouseLeave(emotion);
expect(emotion).not.toHaveClass("scale-150");
});

// Pedro Alonso Moreno Salcedo A01741437 - Test #3/10
it("Should have the right color", () => {
render(
<RulerStepOne
setEmotion={setMockEmotion}
rulerSurveyAnswer={rulerEmotion}
nextStep={nextStepMock}
/>,
);
const emotion = screen.getByTitle(
`emotion-${rulerEmotion.emotion?.energy}-${rulerEmotion.emotion?.pleasantness}`,
);
expect(emotion).toHaveClass(
emotionBgColor(rulerEmotion.emotion as Emotion),
);
});

// Pedro Alonso Moreno Salcedo A01741437 - Test #4/10
it("Should set an emotion", () => {
render(
<RulerStepOne
setEmotion={setMockEmotion}
rulerSurveyAnswer={rulerEmotion}
nextStep={nextStepMock}
/>,
);
const emotion = screen.getByTestId(
`emotion-${randomEmotion.row}-${randomEmotion.col}`,
);
fireEvent.click(emotion);
expect(setMockEmotion).toHaveBeenCalledTimes(1);
});

// Pedro Alonso Moreno Salcedo A01741437 - Test #5/10
it("Should go to the next step", async () => {
render(
<RulerStepOne
setEmotion={setMockEmotion}
rulerSurveyAnswer={rulerEmotion}
nextStep={nextStepMock}
/>,
);
const emotion = screen.getByTestId(
`emotion-${randomEmotion.row}-${randomEmotion.col}`,
);
fireEvent.click(emotion);
await vi.waitUntil(() => nextStepMock.mock.calls.length > 0);
expect(setMockEmotion).toHaveBeenCalledTimes(1);
});
});
70 changes: 70 additions & 0 deletions test/RulerStepTwo.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import RulerStepTwo from "@/components/modals/ruler/RulerStepTwo";
import { RulerSurveyAnswer } from "@/types/types";
import { fireEvent, render, screen } from "@testing-library/react";
import { Mock, describe, expect, it, vi } from "vitest";

let rulerEmotion: RulerSurveyAnswer;
let mockClose: Mock, mockPreviousStep: Mock, mockSetComment: Mock;
describe("RulerSurvey Component Test", () => {
beforeEach(() => {
rulerEmotion = {
userId: "prueba",
emotion: {
name: "",
pleasantness: 2,
description: "",
energy: 2,
id: 1,
},
comment: "",
};
mockClose = vi.fn();
mockPreviousStep = vi.fn();
mockSetComment = vi.fn();
});

// Pedro Alonso Moreno Salcedo A01741437 - Test #6/10
it("Should render step two", () => {
render(
<RulerStepTwo
rulerSurveyAnswer={rulerEmotion}
onClose={mockClose}
previousStep={mockPreviousStep}
setComment={mockSetComment}
/>,
);
expect(screen.getByTestId("ruler-step-two")).toBeInTheDocument();
});

// Pedro Alonso Moreno Salcedo A01741437 - Test #7/10
it("Should set a comment", () => {
render(
<RulerStepTwo
rulerSurveyAnswer={rulerEmotion}
onClose={mockClose}
previousStep={mockPreviousStep}
setComment={mockSetComment}
/>,
);
const comment = screen.getByLabelText(
"Why did you feel this way? (Optional)",
);
fireEvent.change(comment, { target: { value: "test" } });
expect(mockSetComment).toHaveBeenCalledTimes(1);
});

// Pedro Alonso Moreno Salcedo A01741437 - Test #8/10
it("Should go back", () => {
render(
<RulerStepTwo
rulerSurveyAnswer={rulerEmotion}
onClose={mockClose}
previousStep={mockPreviousStep}
setComment={mockSetComment}
/>,
);
const backButton = screen.getByText("Go back");
fireEvent.click(backButton);
expect(mockPreviousStep).toHaveBeenCalledTimes(1);
});
});
31 changes: 31 additions & 0 deletions test/mock-utils/mockUtils.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { DndContext, pointerWithin } from "@dnd-kit/core";
import { RenderOptions, render } from "@testing-library/react";
import React, { ReactElement } from "react";

const DndProvider = ({
children,
onDragEndMock,
}: {
children: React.ReactNode;
onDragEndMock: () => void;
}) => {
return (
<DndContext onDragEnd={onDragEndMock} collisionDetection={pointerWithin}>
{children}
</DndContext>
);
};

export const customDndProvider = (
ui: ReactElement,
onDragEndMock: () => void,
options?: Omit<RenderOptions, "wrapper">,
) =>
render(ui, {
wrapper: (props) => (
<DndProvider {...props} onDragEndMock={onDragEndMock} />
),
...options,
});

export * from "@testing-library/react";

0 comments on commit bd4b69a

Please sign in to comment.