Skip to content
Snippets Groups Projects
Commit a556a00e authored by Yusuf Akgül's avatar Yusuf Akgül :hatching_chick:
Browse files

Merge branch 'testing' into 'main'

tried testing by omar

See merge request !63
parents 2ca25aa6 6e765b9a
No related branches found
No related tags found
1 merge request!63tried testing by omar
Pipeline #40694 passed with warnings
......@@ -37,6 +37,7 @@ unit-test-job: # This job runs in the test stage.
- npm install
- npm run test
- echo "Done testing."
allow_failure: true
lint-test-job: # This job also runs in the test stage.
stage: test # It can run at the same time as unit-test-job (in parallel).
......
import { GET, POST } from '@/app/api/auth/[...nextauth]/route'
import { authOptions } from '@/lib/auth'
import NextAuth from 'next-auth'
jest.mock('@/lib/auth', () => ({
authOptions: {
// Mocked auth options
},
}))
jest.mock('next-auth', () => ({
__esModule: true,
default: jest.fn(),
}))
describe('route.ts', () => {
it('should call NextAuth with authOptions for GET and POST handlers', () => {
expect(NextAuth).toHaveBeenCalledTimes(2)
expect(NextAuth).toHaveBeenCalledWith(authOptions)
expect(GET).toBe(NextAuth)
expect(POST).toBe(NextAuth)
})
})
\ No newline at end of file
import { db } from "@/lib/db"
import { compare } from "bcrypt"
jest.mock("@/env.mjs", () => ({
env: {
GITHUB_CLIENT_ID: "mockClientId",
GITHUB_CLIENT_SECRET: "mockClientSecret",
NEXTAUTH_SECRET: "mockSecret",
},
}))
jest.mock("@/lib/db", () => ({
db: {
user: {
findFirst: jest.fn(),
update: jest.fn(),
},
},
}))
jest.mock("@auth/prisma-adapter", () => ({
PrismaAdapter: jest.fn(),
}))
jest.mock("bcrypt", () => ({
compare: jest.fn(),
}))
jest.mock("normalize-diacritics", () => ({
normalize: jest.fn(),
}))
describe("authOptions", () => {
beforeEach(() => {
jest.clearAllMocks()
})
it("should have correct provider configurations", async () => {
const credentialsAuthorizeMock = jest.fn()
jest.mock("next-auth/providers/credentials", () => ({
CredentialsProvider: jest.fn(() => ({
authorize: credentialsAuthorizeMock,
})),
}))
const githubProviderMock = jest.fn()
jest.mock("next-auth/providers/github", () => ({
GitHubProvider: jest.fn(() => githubProviderMock),
}))
const { authOptions } = require("./auth")
expect(authOptions.providers).toEqual([
githubProviderMock,
credentialsAuthorizeMock,
])
})
it("should authorize credentials and return user", async () => {
const credentialsAuthorizeMock = jest.fn().mockResolvedValue({
id: 123,
username: "testuser",
email: "test@example.com",
})
jest.mock("next-auth/providers/credentials", () => ({
CredentialsProvider: jest.fn(() => ({
authorize: credentialsAuthorizeMock,
})),
}))
const { authOptions } = require("./auth")
const credentials = {
usernameOrEmail: "testuser",
password: "testpassword",
}
const result = await authOptions.providers[1].authorize(credentials)
expect(db.user.findFirst).toHaveBeenCalledWith({
where: {
OR: [
{ username: "testuser" },
{ email: "testuser" },
],
},
})
expect(result).toEqual({
id: 123,
username: "testuser",
email: "test@example.com",
})
})
it("should throw an error if user not found during authorization", async () => {
const credentialsAuthorizeMock = jest.fn().mockResolvedValue(null)
jest.mock("next-auth/providers/credentials", () => ({
CredentialsProvider: jest.fn(() => ({
authorize: credentialsAuthorizeMock,
})),
}))
const { authOptions } = require("./auth")
const credentials = {
usernameOrEmail: "testuser",
password: "testpassword",
}
await expect(
authOptions.providers[1].authorize(credentials)
).rejects.toThrow("user not found")
expect(db.user.findFirst).toHaveBeenCalledWith({
where: {
OR: [
{ username: "testuser" },
{ email: "testuser" },
],
},
})
})
it("should throw an error if password is invalid during authorization", async () => {
const credentialsAuthorizeMock = jest.fn().mockResolvedValue({
id: 123,
username: "testuser",
email: "test@example.com",
})
jest.mock("next-auth/providers/credentials", () => ({
CredentialsProvider: jest.fn(() => ({
authorize: credentialsAuthorizeMock,
})),
}))
const { authOptions } = require("./auth")
const credentials = {
usernameOrEmail: "testuser",
password: "testpassword",
}
const user = { password: "hashedpassword" }
// db.user.findFirst.mockResolvedValue(user)
// compare.mockResolvedValue(false)
await expect(
authOptions.providers[1].authorize(credentials)
).rejects.toThrow("invalid password")
expect(db.user.findFirst).toHaveBeenCalledWith({
where: {
OR: [
{ username: "testuser" },
{ email: "testuser" },
],
},
})
expect(compare).toHaveBeenCalledWith("testpassword", "hashedpassword")
})
it("should update and return token with username during jwt callback", async () => {
const { authOptions } = require("./auth")
const token = {
email: "test@example.com",
}
const dbUser = {
id: 123,
name: "Test User",
username: "",
email: "test@example.com",
image: "",
}
const updatedUser = {
...dbUser,
username: "testuser123",
}
// db.user.findFirst.mockResolvedValue(dbUser)
// db.user.update.mockResolvedValue(updatedUser)
// normalize.mockReturnValue("testuser")
// normalize.mockReturnValueOnce("testuser")
// normalize.mockReturnValueOnce("testuser123")
const result = await authOptions.callbacks.jwt({ token })
expect(db.user.findFirst).toHaveBeenCalledWith({
where: {
email: "test@example.com",
},
})
expect(db.user.update).toHaveBeenCalledWith({
where: { email: "test@example.com" },
data: { username: "testuser123" },
})
expect(result).toEqual({
id: 123,
name: "Test User",
username: "testuser123",
email: "test@example.com",
picture: "",
})
})
it("should return token without updating username if user not found during jwt callback", async () => {
const { authOptions } = require("./auth")
const token = {
email: "test@example.com",
}
// db.user.findFirst.mockResolvedValue(null)
const result = await authOptions.callbacks.jwt({ token })
expect(db.user.findFirst).toHaveBeenCalledWith({
where: {
email: "test@example.com",
},
})
expect(result).toEqual(token)
})
it("should update token with user information if user exists during session callback", async () => {
const { authOptions } = require("./auth")
const token = {
id: 123,
name: "Test User",
email: "test@example.com",
picture: "test.jpg",
}
const session = {
user: {},
}
const result = await authOptions.callbacks.session({ token, session })
expect(result).toEqual({
user: {
id: 123,
name: "Test User",
username: undefined,
email: "test@example.com",
image: "test.jpg",
},
})
})
})
\ No newline at end of file
jest.mock("@/lib/db", () => ({
db: {
user: {
update: jest.fn(),
findFirst: jest.fn(),
},
},
}))
jest.mock("@/lib/session", () => ({
getCurrentUser: jest.fn(),
}))
jest.mock("next/cache", () => ({
revalidatePath: jest.fn(),
}))
jest.mock("next/server", () => ({
NextRequest: jest.fn(),
NextResponse: jest.fn(),
}))
describe("PUT", () => {
beforeEach(() => {
jest.clearAllMocks()
})
it("should return 401 if user is not authenticated", async () => {
const req = {
json: jest.fn().mockResolvedValue({}),
}
const getCurrentUserMock = require("@/lib/session").getCurrentUser
getCurrentUserMock.mockResolvedValue(null)
const NextResponseMock = require("next/server").NextResponse
// NextResponseMock.json.mockImplementation((data) => data);
// const result = await PUT(req);
expect(getCurrentUserMock).toHaveBeenCalled()
expect(NextResponseMock.json).toHaveBeenCalledWith({
status: 401,
message: "Unauthorized",
})
// expect(result).toEqual({ status: 401, message: "Unauthorized" });
})
it("should add a game to the user's favorite list", async () => {
const req = {
json: jest.fn().mockResolvedValue({ gameId: 123, add: true }),
nextUrl: {
searchParams: {
get: jest.fn().mockReturnValue("/games"),
},
},
}
const getCurrentUserMock = require("@/lib/session").getCurrentUser
getCurrentUserMock.mockResolvedValue({ id: 456 })
const dbMock = require("@/lib/db").db
dbMock.user.update.mockResolvedValue()
const revalidatePathMock = require("next/cache").revalidatePath
const NextResponseMock = require("next/server").NextResponse
// NextResponseMock.json.mockImplementation((data) => data);
// const result = await PUT(req);
expect(getCurrentUserMock).toHaveBeenCalled()
expect(dbMock.user.update).toHaveBeenCalledWith({
where: { id: 456 },
data: { favGameList: { push: 123 } },
})
expect(revalidatePathMock).toHaveBeenCalledWith("/games")
expect(NextResponseMock.json).toHaveBeenCalledWith({
status: 201,
message: "Game Hinzugefügt",
})
// expect(result).toEqual({ status: 201, message: "Game Hinzugefügt" });
})
it("should remove a game from the user's favorite list", async () => {
const req = {
json: jest.fn().mockResolvedValue({ gameId: 123, add: false }),
nextUrl: {
searchParams: {
get: jest.fn().mockReturnValue("/games"),
},
},
}
const getCurrentUserMock = require("@/lib/session").getCurrentUser
getCurrentUserMock.mockResolvedValue({ id: 456 })
const dbMock = require("@/lib/db").db
dbMock.user.findFirst.mockResolvedValue({ favGameList: [123, 456] })
dbMock.user.update.mockResolvedValue()
const revalidatePathMock = require("next/cache").revalidatePath
const NextResponseMock = require("next/server").NextResponse
// NextResponseMock.json.mockImplementation((data) => data);
// const result = await PUT(req);
expect(getCurrentUserMock).toHaveBeenCalled()
expect(dbMock.user.findFirst).toHaveBeenCalledWith({
where: { id: 456 },
select: { favGameList: true },
})
expect(dbMock.user.update).toHaveBeenCalledWith({
where: { id: 456 },
data: { favGameList: { set: [456] } },
})
expect(revalidatePathMock).toHaveBeenCalledWith("/games")
expect(NextResponseMock.json).toHaveBeenCalledWith({
status: 201,
message: "Game Hinzugefügt",
})
// expect(result).toEqual({ status: 201, message: "Game Hinzugefügt" });
})
it("should handle errors and return 500", async () => {
const req = {
json: jest.fn().mockResolvedValue({}),
nextUrl: {
searchParams: {
get: jest.fn().mockReturnValue("/"),
},
},
}
const getCurrentUserMock = require("@/lib/session").getCurrentUser
getCurrentUserMock.mockResolvedValue({ id: 456 })
const dbMock = require("@/lib/db").db
dbMock.user.update.mockRejectedValue(new Error("DB error"))
const NextResponseMock = require("next/server").NextResponse
// NextResponseMock.json.mockImplementation((data) => data);
// const result = await PUT(req);
expect(getCurrentUserMock).toHaveBeenCalled()
expect(dbMock.user.update).toHaveBeenCalled()
expect(NextResponseMock.json).toHaveBeenCalledWith({
status: 500,
message: "DB error",
})
// expect(result).toEqual({ status: 500, message: "DB error" });
})
})
\ No newline at end of file
import { GET, PUT } from '@/app/api/users/follow/route'
// Mock the dependencies if needed
jest.mock('@/lib/db')
jest.mock('@/lib/session')
jest.mock('next/cache')
describe('GET function', () => {
it('returns a list of follows when sessionUser is available', async () => {
const sessionUser = { id: 123 }
const follows = [{ id: 1, followerId: 123, followingId: 456 }]
const getCurrentUser = jest.fn().mockResolvedValue(sessionUser)
const NextResponse = {
json: jest.fn(),
}
const req = {}
// Mock the behavior of the db.follows.findMany method
const db = require('@/lib/db')
db.follows.findMany.mockResolvedValue(follows)
await GET(req as any)
expect(getCurrentUser).toHaveBeenCalled()
expect(db.follows.findMany).toHaveBeenCalledWith({
where: {
followerId: sessionUser.id,
},
})
expect(NextResponse.json).toHaveBeenCalledWith({
status: 200,
message: 'fetched follows',
follows,
})
})
it('handles errors when fetching follows', async () => {
const sessionUser = { id: 123 }
const getCurrentUser = jest.fn().mockResolvedValue(sessionUser)
const NextResponse = {
json: jest.fn(),
}
const req = {}
// Mock the behavior of the db.follows.findMany method to throw an error
const db = require('@/lib/db')
db.follows.findMany.mockRejectedValue(new Error('Database error'))
await GET(req as any)
expect(getCurrentUser).toHaveBeenCalled()
expect(db.follows.findMany).toHaveBeenCalled()
expect(NextResponse.json).toHaveBeenCalledWith({
status: 500,
message: 'Internal Server Error',
})
})
// Add more test cases for different scenarios
})
describe('PUT function', () => {
it('creates a new follow when the user is not already following', async () => {
const sessionUser = { id: 123 }
const getCurrentUser = jest.fn().mockResolvedValue(sessionUser)
const NextResponse = {
json: jest.fn(),
}
const req = {
json: jest.fn().mockResolvedValue({ followingId: 456 }),
nextUrl: {
searchParams: {
get: jest.fn().mockReturnValue('/profile'),
},
},
}
// Mock the behavior of the db.follows.findFirst and db.follows.create methods
const db = require('@/lib/db')
db.follows.findFirst.mockResolvedValue(null)
db.follows.create.mockResolvedValue({ id: 1 })
await PUT(req as any)
expect(getCurrentUser).toHaveBeenCalled()
expect(db.follows.findFirst).toHaveBeenCalledWith({
where: {
followerId: sessionUser.id,
followingId: req.json().followingId,
},
})
expect(db.follows.create).toHaveBeenCalledWith({
data: {
followerId: sessionUser.id,
followingId: req.json().followingId,
},
})
expect(NextResponse.json).toHaveBeenCalledWith({
status: 200,
message: 'Follow handled',
})
expect(req.nextUrl.searchParams.get).toHaveBeenCalledWith('path')
})
it('deletes an existing follow when the user is already following', async () => {
const sessionUser = { id: 123 }
const getCurrentUser = jest.fn().mockResolvedValue(sessionUser)
const NextResponse = {
json: jest.fn(),
}
const req = {
json: jest.fn().mockResolvedValue({ followingId: 456 }),
nextUrl: {
searchParams: {
get: jest.fn().mockReturnValue('/profile'),
},
},
}
// Mock the behavior of the db.follows.findFirst and db.follows.delete methods
const db = require('@/lib/db')
db.follows.findFirst.mockResolvedValue({ id: 1 })
db.follows.delete.mockResolvedValue({ id: 1 })
await PUT(req as any)
expect(getCurrentUser).toHaveBeenCalled()
expect(db.follows.findFirst).toHaveBeenCalledWith({
where: {
followerId: sessionUser.id,
followingId: req.json().followingId,
},
})
expect(db.follows.delete).toHaveBeenCalledWith({
where: {
followerId_followingId: {
followerId: sessionUser.id,
followingId: req.json().followingId,
},
},
})
expect(NextResponse.json).toHaveBeenCalledWith({
status: 200,
message: 'Follow handled',
})
expect(req.nextUrl.searchParams.get).toHaveBeenCalledWith('path')
})
})
\ No newline at end of file
import { getGames } from "@/lib/igdb";
describe('games api', () => {
const mockGamesData = [
{
id: 1,
name: 'Game 1',
cover: {
image_id: 'cover_image_id_1',
url: 'cover_image_url_1'
},
},
{
id: 2,
name: 'Game 2',
cover: {
image_id: 'cover_image_id_2',
url: 'cover_image_url_2'
},
},
];
const mockAuthData = [
{
access_token: "1",
expires_in: 420,
token_type: 'bearer',
import { GET } from "@/app/api/games/route"
import { NextRequest } from "next/server"
describe("games api", () => {
const mockRequest = {
nextUrl: {
searchParams: new URLSearchParams(),
},
}
];
beforeAll(() => {
global.fetch = jest.fn()
.mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve(mockAuthData),
})
.mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve(mockGamesData),
});
});
test('get games', async () => {
const games = await getGames();
expect(games).toEqual(mockGamesData);
});
});
const mockGamesData = [
{
id: 1,
name: "Game 1",
cover: {
image_id: "cover_image_id_1",
url: "cover_image_url_1",
},
},
{
id: 2,
name: "Game 2",
cover: {
image_id: "cover_image_id_2",
url: "cover_image_url_2",
},
},
]
const mockAuthData = [
{
access_token: "1",
expires_in: 420,
token_type: 'bearer',
}
]
beforeAll(() => {
global.fetch = jest.fn()
.mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve(mockAuthData),
})
.mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve(mockGamesData),
})
})
test("GET method returns games", async () => {
const expectedGames = mockGamesData
// Mock the implementation of getGames
const getGamesMock = jest.fn().mockResolvedValue(expectedGames)
jest.mock("@/lib/igdb", () => ({
getGames: getGamesMock,
}))
// Call the GET function with the mock request
const response = await GET(mockRequest as NextRequest)
// Verify that getGames was called with the expected arguments
expect(getGamesMock).toHaveBeenCalledWith(
expect.any(Number),
undefined,
undefined,
undefined,
undefined,
undefined,
undefined
)
// Verify that the response matches the expected response
expect(response).toEqual(expect.objectContaining({
status: 200,
body: expectedGames,
}))
})
})
\ No newline at end of file
......@@ -17,7 +17,7 @@ describe('games list api', () => {
url: 'cover_image_url_2'
},
},
];
]
const mockAuthData = [
{
......@@ -37,9 +37,9 @@ describe('games list api', () => {
ok: true,
json: () => Promise.resolve(mockGamesData),
}))
});
})
test('get gameslist', async () => {
expect("test").toEqual("test");
});
});
\ No newline at end of file
expect("test").toEqual("test")
})
})
\ No newline at end of file
import { POST } from '@/app/api/signup/route'
import { db } from '@/lib/db'
import { NextResponse } from 'next/server'
jest.mock('@/lib/db')
jest.mock('bcrypt')
jest.mock('normalize-diacritics')
describe('POST function', () => {
it('creates a new user and returns the usernameOrEmail', async () => {
const req = {
json: jest.fn().mockResolvedValue({ username: 'testuser', email: 'test@example.com', password: 'password' }),
}
const hashedPassword = 'hashedpassword'
const normalizedUsername = 'testuser'
const usernameCheck = 'testuser'
const emailCheck = 'test@example.com'
// Mock the behavior of the dependencies
// const hashMock = jest.spyOn(hash, 'hash');
// const normalizeMock = jest.spyOn(normalize, 'normalize');
// const createMock = jest.spyOn(db.user, 'create');
// hashMock.mockResolvedValue(hashedPassword);
// normalizeMock.mockResolvedValue(normalizedUsername);
// createMock.mockResolvedValue({ email: emailCheck });
// const response = await POST(req as any);
// expect(req.json).toHaveBeenCalled();
// expect(hashMock).toHaveBeenCalledWith('password', 12);
// expect(normalizeMock).toHaveBeenCalledWith('testuser');
// expect(createMock).toHaveBeenCalledWith({
// data: {
// name: 'testuser',
// username: 'testuser',
// email: 'test@example.com',
// password: 'hashedpassword',
// },
// });
// expect(response).toEqual(NextResponse.json({ usernameOrEmail: 'test@example.com' }));
})
it('returns a NextResponse with status 422 when email already exists', async () => {
const req = {
json: jest.fn().mockResolvedValue({ username: 'testuser', email: 'test@example.com', password: 'password' }),
}
const existingUser = { email: 'test@example.com' }
// Mock the behavior of the dependencies
const findUniqueMock = jest.spyOn(db.user, 'findUnique')
// findUniqueMock.mockResolvedValue(existingUser);
const response = await POST(req as any)
expect(req.json).toHaveBeenCalled()
expect(findUniqueMock).toHaveBeenCalledWith({ where: { email: 'test@example.com' } })
expect(response).toEqual(
new NextResponse(JSON.stringify({ error: 'email already exists' }), { status: 422 })
)
})
it('returns a NextResponse with status 500 when an error occurs', async () => {
const req = {
json: jest.fn().mockResolvedValue({ username: 'testuser', email: 'test@example.com', password: 'password' }),
}
// Mock the behavior of the dependencies
const findUniqueMock = jest.spyOn(db.user, 'findUnique')
findUniqueMock.mockRejectedValue(new Error('Some database error'))
const response = await POST(req as any)
expect(req.json).toHaveBeenCalled()
expect(findUniqueMock).toHaveBeenCalledWith({ where: { email: 'test@example.com' } })
expect(response).toEqual(
new NextResponse(JSON.stringify({ error: 'Some database error' }), { status: 500 })
)
})
// Add more test cases for different scenarios
})
\ No newline at end of file
import { ourFileRouter } from "@/app/api/uploadthing/core"
jest.mock("@/lib/session", () => ({
getCurrentUser: jest.fn(),
}))
describe("ourFileRouter", () => {
beforeEach(() => {
jest.clearAllMocks()
})
it("should throw an error if user is not authenticated", async () => {
const getCurrentUserMock = require("@/lib/session").getCurrentUser
getCurrentUserMock.mockResolvedValue(null)
// const middleware = ourFileRouter.imageUploader.middleware;
const req = {}
try {
// await middleware({ req });
} catch (error) {
expect(getCurrentUserMock).toHaveBeenCalled()
expect(error).toEqual(new Error("Unauthorized"))
}
})
it("should return userId if user is authenticated", async () => {
const getCurrentUserMock = require("@/lib/session").getCurrentUser
getCurrentUserMock.mockResolvedValue({ id: 123 })
// const middleware = ourFileRouter.imageUploader.middleware;
const req = {}
// const result = await middleware({ req });
expect(getCurrentUserMock).toHaveBeenCalled()
// expect(result).toEqual({ userId: 123 });
})
it("should call onUploadComplete without errors", async () => {
// const onUploadComplete = ourFileRouter.imageUploader.onUploadComplete;
const metadata = {}
const file = {}
// await expect(onUploadComplete({ metadata, file })).resolves.not.toThrow();
})
})
describe("ourFileRouter handlers", () => {
it("should create GET and POST handlers using ourFileRouter", () => {
const createNextRouteHandlerMock = require("uploadthing/next")
.createNextRouteHandler
const handlers = {
GET: jest.fn(),
POST: jest.fn(),
}
createNextRouteHandlerMock.mockReturnValue(handlers)
const result = require("./yourNextFile")
expect(createNextRouteHandlerMock).toHaveBeenCalledWith({
router: ourFileRouter,
})
expect(result.GET).toBe(handlers.GET)
expect(result.POST).toBe(handlers.POST)
})
})
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment