Skip to content

Commit

Permalink
add some tests
Browse files Browse the repository at this point in the history
  • Loading branch information
MaximeDan committed Jun 18, 2024
1 parent 0d1d0c7 commit 3df7169
Show file tree
Hide file tree
Showing 14 changed files with 119 additions and 110 deletions.
126 changes: 74 additions & 52 deletions __test__/auth/apiClient/registerUserApi.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,68 +3,90 @@
*/

import { testApiHandler } from "next-test-api-route-handler";

import * as registerHandler from "../../../src/app/api/auth/register/route";

describe("/api/auth/register", () => {
it("registers a new user successfully", async () => {
await testApiHandler({
appHandler: registerHandler,
test: async ({ fetch }) => {
const res = await fetch({
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
it("registers a new user successfully", async () => {
await testApiHandler({
appHandler: registerHandler,
test: async ({ fetch }) => {
const res = await fetch({
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
email: "[email protected]",
password: "Password@123",
username: "johndoe",
name: "John",
lastName: "Doe",
dateOfBirth: new Date("1990-01-01"),
}),
});
const data = await res.json();

expect(res.status).toBe(201);
expect(data).toEqual(
expect.objectContaining({
user: expect.objectContaining({
email: "[email protected]",
password: "Password@123",
username: "johndoe",
name: "John",
lastName: "Doe",
dateOfBirth: new Date("1990-01-01"),
}),
});
const data = await res.json();
}),
);
},
});
});

expect(res.status).toBe(201);
expect(data).toEqual(
expect.objectContaining({
user: expect.objectContaining({
email: "[email protected]",
username: "johndoe",
name: "John",
lastName: "Doe",
}),
}),
);
},
});
it("returns error for already used email", async () => {
await testApiHandler({
appHandler: registerHandler,
test: async ({ fetch }) => {
const res = await fetch({
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: "Alice",
lastName: "Prisma",
email: "[email protected]",
username: "aliceUserName",
password: "alicePassword",
dateOfBirth: new Date("1990-01-01"),
}),
});
const data = await res.json();

expect(res.status).toBe(400);
expect(data).toEqual(
expect.objectContaining({
message: "Email already in use",
}),
);
},
});
});

it("returns error for already used email", async () => {
await testApiHandler({
appHandler: registerHandler,
test: async ({ fetch }) => {
const res = await fetch({
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: "Alice",
lastName: "Prisma",
email: "[email protected]",
username: "aliceUserName",
password: "alicePassword",
dateOfBirth: new Date("1990-01-01"),
}),
});
const data = await res.json();
it("returns error for bad request", async () => {
await testApiHandler({
appHandler: registerHandler,
test: async ({ fetch }) => {
const res = await fetch({
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
name: "Alice",
lastName: "Prisma",
email: "",
}),
});
const data = await res.json();

expect(res.status).toBe(400);
expect(data).toEqual(
expect.objectContaining({
message: "Email already in use",
}),
);
},
});
expect(res.status).toBe(400);
expect(data).toEqual(
expect.objectContaining({
message: "email is required",
}),
);
},
});
});
Empty file added __test__/auth/loginUser.test.ts
Empty file.
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ describe("registerSchema", () => {

expect(() => registerSchema.parse(invalidData)).toThrow();
});

it("should throw error for password mismatch", () => {
const invalidData = {
name: "John",
Expand All @@ -44,5 +43,4 @@ describe("registerSchema", () => {
expect(() => registerSchema.parse(invalidData)).toThrow();
});

// Add more tests for other invalid cases as needed
});
11 changes: 0 additions & 11 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@
"@types/react": "^18",
"@types/react-dom": "^18",
"@types/supertest": "^6.0.2",
"@types/testing-library__jest-dom": "^6.0.0",
"dotenv": "^16.4.5",
"eslint": "^8.57.0",
"eslint-config-next": "14.2.3",
Expand Down
2 changes: 1 addition & 1 deletion runIntegrationTests.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ const seedDatabase = async () => {

const runTests = async () => {
console.log("Running tests...");
await execPromise("npx jest --runInBand");
await execPromise("npx jest");
};

const stopDocker = async () => {
Expand Down
1 change: 1 addition & 0 deletions src/app/api/auth/[...nextauth]/route.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import NextAuth from "next-auth";
import { authOptions } from "@/lib/authOptions";

// @ts-ignore
const handler = NextAuth(authOptions);

export { handler as GET, handler as POST };
14 changes: 14 additions & 0 deletions src/app/api/auth/register/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from "next/server";
import { register } from "@/services/userService";
import { RegisterUser } from "@/types/register";
import { handleException } from "@/app/utils/errorHandlerUtils";
import { BadRequestException } from "@/types/exceptions";

/**
* @params request: NextRequest
Expand All @@ -12,6 +13,19 @@ async function handler(request: NextRequest): Promise<NextResponse> {
const data = await request.json();

try {
const requiredFields = [
"email",
"password",
"username",
"name",
"lastName",
"dateOfBirth",
];
for (const field of requiredFields) {
if (!data[field]) {
throw new BadRequestException(`${field} is required`);
}
}
const userData: RegisterUser = {
email: data.email,
password: data.password,
Expand Down
6 changes: 1 addition & 5 deletions src/app/api/users/[id]/route.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
import { handleException } from "@/app/utils/errorHandlerUtils";
import {
getUserById,
modifyUser,
removeUser,
} from "@/services/userService";
import { getUserById, modifyUser, removeUser } from "@/services/userService";
import { User } from "@prisma/client";
import { NextRequest, NextResponse } from "next/server";

Expand Down
26 changes: 2 additions & 24 deletions src/app/api/users/route.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import { handleException } from "@/app/utils/errorHandlerUtils";
import {
getAllUsers,
} from "@/services/userService";
import { User } from "@prisma/client";
import { NextRequest, NextResponse } from "next/server";
import { getAllUsers } from "@/services/userService";
import { NextResponse } from "next/server";

/**
* @returns NextResponse
Expand All @@ -17,22 +14,3 @@ export async function GET() {
return handleException(error);
}
}


/**
* @params request: NextRequest
* @returns NextResponse
* @description Handles PUT request to modify an existing user.
*/
export async function PUT(request: NextRequest) {
try {
const body = await request.json();
const userId: string = body.userId;
const user: User = body.user;

const result = await registerOrModifyUser(userId, user);
return NextResponse.json({ data: result }, { status: 200 });
} catch (error: any) {
return handleException(error);
}
}
2 changes: 1 addition & 1 deletion src/repositories/userEventRepository.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import prisma from "@/lib/prisma";
import { UserEventWithoutId } from "@/types/userEventNullableId";
import { UserEventWithoutId } from "@/types/userEventWithoutId";
import { UserEvent } from "@prisma/client";

/**
Expand Down
8 changes: 1 addition & 7 deletions src/services/userService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,7 @@ import bcrypt from "bcrypt";
import { getRoleById } from "./roleService";
import { RegisterUser } from "@/types/register";
import { UserRoleData } from "@/types/userRole";
import {
BadRequestException,
InternalServerErrorException,
NotFoundException,
} from "@/types/exceptions";
import { BadRequestException, NotFoundException } from "@/types/exceptions";

/**
* @params userData: RegisterUser
Expand All @@ -31,8 +27,6 @@ export const register = async (userData: RegisterUser): Promise<User> => {
if (existingUser) throw new BadRequestException("Email already in use");

userData.password = await bcrypt.hash(userData.password, 10);
if (!userData.password)
throw new InternalServerErrorException("Password not hashed");

const userRole = await getRoleById(1);
if (!userRole) throw new NotFoundException("Role not found");
Expand Down
1 change: 1 addition & 0 deletions src/types/next-auth.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ declare module "next-auth" {
id: number;
dateOfBirth: Date;
}
// eslint-disable-next-line no-unused-vars
interface Session {
user: User;
}
Expand Down
29 changes: 23 additions & 6 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
{
"compilerOptions": {
"lib": ["dom", "dom.iterable", "esnext"],
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
Expand All @@ -18,9 +22,22 @@
}
],
"paths": {
"@/*": ["./src/*"]
}
"@/*": [
"./src/*"
]
},
"types": [
"@types/jest"
]
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", "runIntegrationTests.js"],
"exclude": ["node_modules"]
}
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
"runIntegrationTests.js"
],
"exclude": [
"node_modules"
]
}

0 comments on commit 3df7169

Please sign in to comment.