Skip to content

Commit

Permalink
Added tests
Browse files Browse the repository at this point in the history
  • Loading branch information
davidcrair committed Apr 13, 2024
1 parent 208af2e commit 15cfaaf
Show file tree
Hide file tree
Showing 33 changed files with 36,303 additions and 1,145 deletions.
4 changes: 4 additions & 0 deletions .babelrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"presets": ["@babel/preset-env"]
}

14 changes: 14 additions & 0 deletions __tests__/error.t.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/* eslint-disable react/jsx-filename-extension */

import React from "react";
import { render, screen, fireEvent } from "@testing-library/react";
import ErrorAlert from "@/app/error/error";

describe("ErrorAlert Component Tests", () => {
// Test for proper rendering with props
it("renders with given title and message", () => {
render(<ErrorAlert Title="Error" Message="An error has occurred" />);
expect(screen.getByText("Error")).toBeInTheDocument();
expect(screen.getByText("An error has occurred")).toBeInTheDocument();
});
});
79 changes: 79 additions & 0 deletions __tests__/spotify_code_generator.t.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import axios from "axios";

import {
hashCode,
getColorFromSeed,
modifySvg,
GetSpotifyCode,
} from "@/components/SpotifyCodeGenerator";

jest.mock("axios");

describe("hashCode", () => {
test("should compute hash code correctly", () => {
expect(hashCode("hello")).toBe(hashCode("hello"));
expect(hashCode("hello")).not.toBe(hashCode("hello "));
});

test("should return 0 for empty string", () => {
expect(hashCode("")).toBe(0);
});
});

describe("getColorFromSeed", () => {
test("should generate consistent color from seed", () => {
const seed = 0.5;
expect(getColorFromSeed(seed)).toBe(getColorFromSeed(seed));
});

test("should generate a valid hex color code", () => {
const seed = 0.1;
expect(getColorFromSeed(seed)).toMatch(/^#([0-9A-F]{6})$/i);
});
});

describe("modifySvg", () => {
test("should modify SVG and add rectangles with specific attributes", () => {
const mockSvgString =
'<svg><rect fill="#ffffff"></rect><rect fill="#000000"></rect></svg>';
const uri = "testuri";
global.DOMParser = jest.fn().mockImplementation(() => ({
parseFromString: jest.fn().mockReturnValue({
querySelectorAll: jest.fn().mockReturnValue([]),
querySelector: jest.fn().mockReturnValue({
insertBefore: jest.fn(),
}),
createElementNS: jest.fn().mockReturnValue({
setAttribute: jest.fn(),
}),
}),
createElementNS: jest.fn(),
}));
global.XMLSerializer = jest.fn().mockImplementation(() => ({
serializeToString: jest.fn().mockReturnValue("modifiedSvg"),
}));

const result = modifySvg(mockSvgString, uri);
expect(result).toBe("modifiedSvg");
});
});

describe("GetSpotifyCode", () => {
// Test successful SVG retrieval and modification
it("retrieves and modifies an SVG correctly", async () => {
const fakeSVG = "<svg>...</svg>"; // Simplified SVG for testing
const expectedURI = "track:6rqhFgbbKwnb9MLmUQDhG6";
const modifiedSVG = modifySvg(fakeSVG, expectedURI);

// Mock axios response
axios.get.mockResolvedValue({
data: Buffer.from(fakeSVG),
});

const result = await GetSpotifyCode(
"https://spotify.com/track/6rqhFgbbKwnb9MLmUQDhG6",
);
expect(result).toEqual(modifiedSVG);
expect(axios.get).toHaveBeenCalled();
});
});
110 changes: 110 additions & 0 deletions __tests__/unify.t copy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/* eslint-disable react/jsx-filename-extension */

import { render, fireEvent, waitFor } from "@testing-library/react";

import {
calculateGenreSimilarity,
calculateArtistSimilarity,
featureDataSimilarity,
VinylCircle,
GenrePieChart,
UnifyContent,
} from "@/app/unify/[users]/UnifyContent";

import userData from "./userData.json";

class MockImage {
constructor() {
setTimeout(() => this.onload(), 100); // Ensure onload is called
}

src = "";
}

global.Image = MockImage;

const mockGetContext = jest.fn(() => ({
drawImage: jest.fn(),
fillText: jest.fn(),
strokeText: jest.fn(),
clearRect: jest.fn(),
}));

global.HTMLCanvasElement.prototype.getContext = mockGetContext;

global.navigator.share = jest.fn(() => Promise.resolve());

// mock nivio because it was causing jest issues
jest.mock("@nivo/radar", () => ({ ResponsiveRadar: () => "ResponsiveRadar" }));
jest.mock("@nivo/pie", () => ({ ResponsivePie: () => "ResponsivePie" }));

describe("calculateGenreSimilarity", () => {
test("returns 100% for identical genre lists", () => {
const genresA = { rock: 5, jazz: 3 };
const genresB = { rock: 5, jazz: 3 };
expect(calculateGenreSimilarity(genresA, genresB)).toBe(100);
});

test("returns 0% for completely different genre lists", () => {
const genresA = { rock: 5 };
const genresB = { classical: 3 };
expect(calculateGenreSimilarity(genresA, genresB)).toBe(0);
});

test("calculates correct percentage for partially overlapping genres", () => {
const genresA = { rock: 5, jazz: 3 };
const genresB = { rock: 5, blues: 2 };
expect(calculateGenreSimilarity(genresA, genresB)).toBe(33);
});
});

describe("calculateArtistSimilarity", () => {
test("calculateArtistSimilarity calculates correct similarity", () => {
const artists1 = ["Artist A", "Artist B", "Artist C"];
const artists2 = ["Artist B", "Artist A", "Artist D"];
expect(calculateArtistSimilarity(artists1, artists2)).toBe(20);
});
});

describe("featureDataSimilarity", () => {
test("featureDataSimilarity returns correct similarity", () => {
const features1 = [{ value: 10 }, { value: 30 }];
const features2 = [{ value: 10 }, { value: 40 }];
expect(featureDataSimilarity(features1, features2)).toBe(90);
});
});

describe("VinylCircle Component", () => {
test("renders correctly with given props", () => {
const { getByTestId } = render(
<VinylCircle centerCircleColor="black" width={300} />,
);
const svg = getByTestId("VinylCircle");
expect(svg).toBeTruthy();
});
});

describe("GenrePieChart Component", () => {
const mockData = {
topGenres: [
{ id: "rock", value: 10 },
{ id: "jazz", value: 20 },
],
};

test("renders correctly with given props", () => {
const { getByTestId } = render(
<GenrePieChart data={mockData} centerCircleColor="black" />,
);
const svg = getByTestId("GenrePieChart");
expect(svg).toBeTruthy();
});
});

describe("UnifyContent", () => {
it("renders UnifyContent correctly with provided data", () => {
const { getByText } = render(
<UnifyContent user1Data={userData} user2Data={userData} />,
);
});
});
110 changes: 110 additions & 0 deletions __tests__/unify.t.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/* eslint-disable react/jsx-filename-extension */

import { render, fireEvent, waitFor } from "@testing-library/react";

import {
calculateGenreSimilarity,
calculateArtistSimilarity,
featureDataSimilarity,
VinylCircle,
GenrePieChart,
UnifyContent,
} from "@/app/unify/[users]/UnifyContent";

import userData from "./userData.json";

class MockImage {
constructor() {
setTimeout(() => this.onload(), 100); // Ensure onload is called
}

src = "";
}

global.Image = MockImage;

const mockGetContext = jest.fn(() => ({
drawImage: jest.fn(),
fillText: jest.fn(),
strokeText: jest.fn(),
clearRect: jest.fn(),
}));

global.HTMLCanvasElement.prototype.getContext = mockGetContext;

global.navigator.share = jest.fn(() => Promise.resolve());

// mock nivio because it was causing jest issues
jest.mock("@nivo/radar", () => ({ ResponsiveRadar: () => "ResponsiveRadar" }));
jest.mock("@nivo/pie", () => ({ ResponsivePie: () => "ResponsivePie" }));

describe("calculateGenreSimilarity", () => {
test("returns 100% for identical genre lists", () => {
const genresA = { rock: 5, jazz: 3 };
const genresB = { rock: 5, jazz: 3 };
expect(calculateGenreSimilarity(genresA, genresB)).toBe(100);
});

test("returns 0% for completely different genre lists", () => {
const genresA = { rock: 5 };
const genresB = { classical: 3 };
expect(calculateGenreSimilarity(genresA, genresB)).toBe(0);
});

test("calculates correct percentage for partially overlapping genres", () => {
const genresA = { rock: 5, jazz: 3 };
const genresB = { rock: 5, blues: 2 };
expect(calculateGenreSimilarity(genresA, genresB)).toBe(33);
});
});

describe("calculateArtistSimilarity", () => {
test("calculateArtistSimilarity calculates correct similarity", () => {
const artists1 = ["Artist A", "Artist B", "Artist C"];
const artists2 = ["Artist B", "Artist A", "Artist D"];
expect(calculateArtistSimilarity(artists1, artists2)).toBe(20);
});
});

describe("featureDataSimilarity", () => {
test("featureDataSimilarity returns correct similarity", () => {
const features1 = [{ value: 10 }, { value: 30 }];
const features2 = [{ value: 10 }, { value: 40 }];
expect(featureDataSimilarity(features1, features2)).toBe(90);
});
});

describe("VinylCircle Component", () => {
test("renders correctly with given props", () => {
const { getByTestId } = render(
<VinylCircle centerCircleColor="black" width={300} />,
);
const svg = getByTestId("VinylCircle");
expect(svg).toBeTruthy();
});
});

describe("GenrePieChart Component", () => {
const mockData = {
topGenres: [
{ id: "rock", value: 10 },
{ id: "jazz", value: 20 },
],
};

test("renders correctly with given props", () => {
const { getByTestId } = render(
<GenrePieChart data={mockData} centerCircleColor="black" />,
);
const svg = getByTestId("GenrePieChart");
expect(svg).toBeTruthy();
});
});

describe("UnifyContent", () => {
it("renders UnifyContent correctly with provided data", () => {
const { getByText } = render(
<UnifyContent user1Data={userData} user2Data={userData} />,
);
});
});
58 changes: 58 additions & 0 deletions __tests__/user.t.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/* eslint-disable react/jsx-filename-extension */

import React from "react";
import { render, waitFor } from "@testing-library/react";
import UserPage from "@/app/user/[slug]/page";
import createClient from "@/utils/supabase/client";

jest.mock("../src/utils/supabase/client", () => ({
__esModule: true,
default: jest.fn(),
}));

jest.mock(
"../src/components/svg-art/user_content",
() =>
function () {
return <div>UserContent Component</div>;
},
);
jest.mock(
"../src/app/error/error",
() =>
function ({ Title, Message }) {
return (
<div>
{Title}
{Message}
</div>
);
},
);

global.navigator.share = jest.fn();

HTMLCanvasElement.prototype.getContext = jest.fn(() => ({
drawImage: jest.fn(),
fillText: jest.fn(),
clearRect: jest.fn(),
toBlob: jest.fn((callback) => callback("blob")),
}));

beforeEach(() => {
createClient.mockImplementation(() => ({
from: jest.fn().mockReturnThis(),
select: jest.fn().mockReturnThis(),
eq: jest.fn().mockResolvedValue({
data: [{ spotify_data: { username: "user1" } }],
error: null,
}),
}));
});

it("fetches user data successfully and renders UserContent", async () => {
const { findByText } = render(<UserPage params={{ slug: "userSlug" }} />);
await waitFor(() => {
expect(findByText("UserContent Component")).toBeTruthy();
});
});
Loading

0 comments on commit 15cfaaf

Please sign in to comment.