Fix tests to correctly handle AppError mock and instance checks

This commit is contained in:
NouhailaAater 2025-02-27 01:03:56 -05:00
parent d2bf18b88d
commit fc69a37e53
2 changed files with 16 additions and 54 deletions

View file

@ -1,47 +1,43 @@
jest.mock("../middleware/AppError", () => {
return jest.fn((message, code) => {
const error = new Error(message);
error.code = code;
return error;
});
});
const AppError = require("../middleware/AppError"); const AppError = require("../middleware/AppError");
jest.mock("../middleware/AppError", () => {
const actualAppError = jest.requireActual("../middleware/AppError");
return jest.fn().mockImplementation((message, statusCode) => {
return new actualAppError(message, statusCode);
});
});
const Rooms = require("../models/room"); const Rooms = require("../models/room");
const ObjectId = require("mongodb").ObjectId; const ObjectId = require("mongodb").ObjectId;
describe("Rooms", () => { describe("Rooms", () => {
let rooms; let rooms;
let db; let db;
let collection; let collection;
beforeEach(() => { beforeEach(() => {
jest.clearAllMocks(); // Clear any previous mock calls jest.clearAllMocks();
// Mock the collection object
collection = { collection = {
findOne: jest.fn(), findOne: jest.fn(),
insertOne: jest.fn(), insertOne: jest.fn(),
find: jest.fn().mockReturnValue({ toArray: jest.fn() }), // Mock the find method find: jest.fn().mockReturnValue({ toArray: jest.fn() }),
deleteOne: jest.fn(), deleteOne: jest.fn(),
deleteMany: jest.fn(), deleteMany: jest.fn(),
updateOne: jest.fn(), updateOne: jest.fn(),
}; };
// Mock the database connection
db = { db = {
connect: jest.fn(), connect: jest.fn(),
getConnection: jest.fn().mockReturnThis(), // Add getConnection method getConnection: jest.fn().mockReturnThis(),
collection: jest.fn().mockReturnValue(collection), collection: jest.fn().mockReturnValue(collection),
}; };
rooms = new Rooms(db); rooms = new Rooms(db);
}); });
// create
describe("create", () => { describe("create", () => {
it("should return insertedId on success", async () => { it("should return insertedId on success", async () => {
// Mock d'une création réussie
collection.findOne.mockResolvedValue(null); collection.findOne.mockResolvedValue(null);
collection.insertOne.mockResolvedValue({ insertedId: "abc123" }); collection.insertOne.mockResolvedValue({ insertedId: "abc123" });
@ -49,14 +45,12 @@ describe("Rooms", () => {
expect(result).toBe("abc123"); expect(result).toBe("abc123");
}); });
// throw an error if userId is undefined
it("should throw error when userId is missing", async () => { it("should throw error when userId is missing", async () => {
await expect(rooms.create("test", undefined)).rejects.toThrow( await expect(rooms.create("test", undefined)).rejects.toThrowError(
"AppError is not defined" new AppError("Missing required parameter(s)", 400)
); );
}); });
// throw an error if room exists
it("should throw conflict error when room exists", async () => { it("should throw conflict error when room exists", async () => {
collection.findOne.mockResolvedValue({ collection.findOne.mockResolvedValue({
_id: "660c72b2f9b1d8b3a4c8e4d3b", _id: "660c72b2f9b1d8b3a4c8e4d3b",
@ -64,13 +58,11 @@ describe("Rooms", () => {
title: "existing room", title: "existing room",
}); });
await expect(rooms.create("existing room", "12345")).rejects.toThrow( await expect(rooms.create("existing room", "12345")).rejects.toThrowError(
"AppError is not defined" new AppError("Une salle avec ce nom existe déjà", 409)
); );
}); });
}); });
// getUserRooms
describe("getUserRooms", () => { describe("getUserRooms", () => {
it("should return all rooms for a user", async () => { it("should return all rooms for a user", async () => {
const userId = "12345"; const userId = "12345";
@ -79,7 +71,6 @@ describe("Rooms", () => {
{ title: "room 2", userId }, { title: "room 2", userId },
]; ];
// Mock the database response
collection.find().toArray.mockResolvedValue(userRooms); collection.find().toArray.mockResolvedValue(userRooms);
const result = await rooms.getUserRooms(userId); const result = await rooms.getUserRooms(userId);
@ -91,13 +82,11 @@ describe("Rooms", () => {
}); });
}); });
// getOwner
describe("getOwner", () => { describe("getOwner", () => {
it("should return the owner of a room", async () => { it("should return the owner of a room", async () => {
const roomId = "60c72b2f9b1d8b3a4c8e4d3b"; const roomId = "60c72b2f9b1d8b3a4c8e4d3b";
const userId = "12345"; const userId = "12345";
// Mock the database response
collection.findOne.mockResolvedValue({ userId }); collection.findOne.mockResolvedValue({ userId });
const result = await rooms.getOwner(roomId); const result = await rooms.getOwner(roomId);
@ -115,7 +104,6 @@ describe("Rooms", () => {
it("should delete a room and return true", async () => { it("should delete a room and return true", async () => {
const roomId = "60c72b2f9b1d8b3a4c8e4d3b"; const roomId = "60c72b2f9b1d8b3a4c8e4d3b";
// Mock the database response
collection.deleteOne.mockResolvedValue({ deletedCount: 1 }); collection.deleteOne.mockResolvedValue({ deletedCount: 1 });
const result = await rooms.delete(roomId); const result = await rooms.delete(roomId);
@ -131,7 +119,6 @@ describe("Rooms", () => {
it("should return false if the room does not exist", async () => { it("should return false if the room does not exist", async () => {
const roomId = "60c72b2f9b1d8b3a4c8e4d3b"; const roomId = "60c72b2f9b1d8b3a4c8e4d3b";
// Mock the database response
collection.deleteOne.mockResolvedValue({ deletedCount: 0 }); collection.deleteOne.mockResolvedValue({ deletedCount: 0 });
const result = await rooms.delete(roomId); const result = await rooms.delete(roomId);
@ -145,21 +132,18 @@ describe("Rooms", () => {
}); });
}); });
// rename
describe("rename", () => { describe("rename", () => {
it("should rename a room and return true", async () => { it("should rename a room and return true", async () => {
const roomId = "60c72b2f9b1d8b3a4c8e4d3b"; const roomId = "60c72b2f9b1d8b3a4c8e4d3b";
const newTitle = "new room name"; const newTitle = "new room name";
const userId = "12345"; const userId = "12345";
// Mock the database response
collection.updateOne.mockResolvedValue({ modifiedCount: 1 }); collection.updateOne.mockResolvedValue({ modifiedCount: 1 });
const result = await rooms.rename(roomId, userId, newTitle); const result = await rooms.rename(roomId, userId, newTitle);
expect(db.connect).toHaveBeenCalled(); expect(db.connect).toHaveBeenCalled();
expect(db.collection).toHaveBeenCalledWith("rooms"); expect(db.collection).toHaveBeenCalledWith("rooms");
// { _id: ObjectId.createFromHexString(roomId), userId: userId }, { $set: { title: newTitle } }
expect(collection.updateOne).toHaveBeenCalledWith( expect(collection.updateOne).toHaveBeenCalledWith(
{ _id: new ObjectId(roomId), userId: userId }, { _id: new ObjectId(roomId), userId: userId },
{ $set: { title: newTitle } } { $set: { title: newTitle } }
@ -172,7 +156,6 @@ describe("Rooms", () => {
const newTitle = "new room name"; const newTitle = "new room name";
const userId = "12345"; const userId = "12345";
// Mock the database response
collection.updateOne.mockResolvedValue({ modifiedCount: 0 }); collection.updateOne.mockResolvedValue({ modifiedCount: 0 });
const result = await rooms.rename(roomId, userId, newTitle); const result = await rooms.rename(roomId, userId, newTitle);
@ -191,7 +174,6 @@ describe("Rooms", () => {
const newTitle = "existing room"; const newTitle = "existing room";
const userId = "12345"; const userId = "12345";
// Mock the database response
collection.findOne.mockResolvedValue({ title: newTitle }); collection.findOne.mockResolvedValue({ title: newTitle });
collection.updateOne.mockResolvedValue({ modifiedCount: 0 }); collection.updateOne.mockResolvedValue({ modifiedCount: 0 });
@ -212,7 +194,6 @@ describe("Rooms", () => {
it("should return true if room exists", async () => { it("should return true if room exists", async () => {
const title = "test room"; const title = "test room";
// Mock the database response
collection.findOne.mockResolvedValue({ title }); collection.findOne.mockResolvedValue({ title });
const result = await rooms.roomExists(title); const result = await rooms.roomExists(title);
@ -225,7 +206,6 @@ describe("Rooms", () => {
it("should return false if room does not exist", async () => { it("should return false if room does not exist", async () => {
const title = "nonexistent room"; const title = "nonexistent room";
// Mock the database response
collection.findOne.mockResolvedValue(null); collection.findOne.mockResolvedValue(null);
const result = await rooms.roomExists(title); const result = await rooms.roomExists(title);
@ -237,7 +217,6 @@ describe("Rooms", () => {
}); });
}); });
// write a test for getRoomById
describe("getRoomById", () => { describe("getRoomById", () => {
it("should return a room by ID", async () => { it("should return a room by ID", async () => {
const roomId = "60c72b2f9b1d8b3a4c8e4d3b"; const roomId = "60c72b2f9b1d8b3a4c8e4d3b";
@ -246,7 +225,6 @@ describe("Rooms", () => {
title: "test room", title: "test room",
}; };
// Mock the database response
collection.findOne.mockResolvedValue(room); collection.findOne.mockResolvedValue(room);
const result = await rooms.getRoomById(roomId); const result = await rooms.getRoomById(roomId);
@ -262,11 +240,10 @@ describe("Rooms", () => {
it("should throw an error if the room does not exist", async () => { it("should throw an error if the room does not exist", async () => {
const roomId = "60c72b2f9b1d8b3a4c8e4d3b"; const roomId = "60c72b2f9b1d8b3a4c8e4d3b";
// Mock the database response
collection.findOne.mockResolvedValue(null); collection.findOne.mockResolvedValue(null);
await expect(rooms.getRoomById(roomId)).resolves.toThrow( await expect(rooms.getRoomById(roomId)).rejects.toThrowError(
`Room ${roomId} not found` new AppError(`Room ${roomId} not found`, 404)
); );
expect(db.connect).toHaveBeenCalled(); expect(db.connect).toHaveBeenCalled();

View file

@ -1,17 +1,8 @@
const AppError = require("./AppError"); const AppError = require("./AppError");
const fs = require('fs');
const errorHandler = (error, req, res, _next) => { const errorHandler = (error, req, res, _next) => {
res.setHeader('Cache-Control', 'no-store'); res.setHeader('Cache-Control', 'no-store');
// Debug
console.log("Erreur reçue :", {
message: error.message,
stack: error.stack,
constructor: error.constructor.name,
proto: Object.getPrototypeOf(error)
});
if (error instanceof AppError) { if (error instanceof AppError) {
return res.status(error.statusCode).json({ return res.status(error.statusCode).json({
message: error.message, message: error.message,
@ -25,10 +16,4 @@ const errorHandler = (error, req, res, _next) => {
}); });
}; };
const logError = (error) => {
const time = new Date();
var log_file = fs.createWriteStream(__dirname + '/../debug.log', {flags : 'a'});
log_file.write(time + '\n' + error + '\n\n');
}
module.exports = errorHandler; module.exports = errorHandler;