EvalueTonSavoir/server/__tests__/image.test.js

355 lines
13 KiB
JavaScript
Raw Permalink Normal View History

/* eslint-disable */
2024-10-03 12:05:20 -04:00
// const request = require('supertest');
// const app = require('../app.js');
// // const app = require('../routers/images.js');
// const { response } = require('express');
2024-03-29 20:08:34 -04:00
2024-10-03 12:05:20 -04:00
// const BASE_URL = '/image'
2024-03-29 20:08:34 -04:00
2025-02-22 17:56:53 -05:00
const Images = require('../models/images');
const ObjectId = require('mongodb').ObjectId;
2024-10-03 12:05:20 -04:00
describe.skip("POST /upload", () => {
2024-03-29 20:08:34 -04:00
describe("when the jwt is not sent", () => {
test('should respond with 401 status code', async () => {
const response = await request(app).post(BASE_URL + "/upload").send()
expect(response.statusCode).toBe(401)
})
// respond message Accès refusé. Aucun jeton fourni.
})
describe("when sent bad jwt", () => {
// respond with 401
// respond message Accès refusé. Jeton invalide.
})
describe("when sent no variables", () => {
// respond message Paramètre requis manquant.
// respond code 400
})
describe("when sent not an image file", () => {
// respond code 505
})
describe("when sent image file", () => {
// respond code 200
// json content type
// test("should reply with content type json", async () => {
// const response = await request(app).post(BASE_URL+'/upload').send()
// expect(response.headers['content-type']).toEqual(expect.stringContaining('json'))
// })
})
})
2024-10-03 12:05:20 -04:00
describe.skip("GET /get", () => {
2024-03-29 20:08:34 -04:00
describe("when not give id", () => {
})
describe("when not good id", () => {
})
describe("when good id", () => {
// respond code 200
// image content type
// response has something
})
2024-10-03 12:05:20 -04:00
})
2025-02-22 17:56:53 -05:00
2025-03-14 01:56:53 -04:00
jest.mock('mongodb', () => {
const originalModule = jest.requireActual('mongodb');
return {
...originalModule,
ObjectId: {
...originalModule.ObjectId,
createFromHexString: jest.fn().mockReturnValue('507f191e810c19729de860ea'), // Return a valid 24-character ObjectId string
},
};
});
2025-02-22 17:56:53 -05:00
describe('Images', () => {
let db;
let images;
let dbConn;
let mockImagesCollection;
2025-03-10 19:03:58 -04:00
let mockFindCursor;
2025-02-22 17:56:53 -05:00
beforeEach(() => {
2025-03-14 01:56:53 -04:00
const mockImagesCursor = {
sort: jest.fn().mockReturnThis(),
skip: jest.fn().mockReturnThis(),
limit: jest.fn().mockReturnThis(),
toArray: jest.fn()
};
const mockFilesCursor = {
sort: jest.fn().mockReturnThis(),
skip: jest.fn().mockReturnThis(),
limit: jest.fn().mockReturnThis(),
toArray: jest.fn()
};
2025-03-10 19:03:58 -04:00
2025-02-22 17:56:53 -05:00
mockImagesCollection = {
insertOne: jest.fn().mockResolvedValue({ insertedId: 'image123' }),
2025-02-24 20:26:30 -05:00
findOne: jest.fn(),
2025-03-14 01:56:53 -04:00
find: jest.fn().mockReturnValue(mockImagesCursor),
2025-03-13 18:02:26 -04:00
countDocuments: jest.fn(),
2025-03-14 01:56:53 -04:00
deleteOne: jest.fn()
2025-02-22 17:56:53 -05:00
};
2025-03-14 01:56:53 -04:00
mockFilesCollection = {
find: jest.fn().mockReturnValue(mockFilesCursor)
};
2025-02-22 17:56:53 -05:00
dbConn = {
2025-03-14 01:56:53 -04:00
collection: jest.fn((name) => {
if (name === 'images') {
return mockImagesCollection;
} else if (name === 'files') {
return mockFilesCollection;
}
})
2025-02-22 17:56:53 -05:00
};
db = {
connect: jest.fn().mockResolvedValue(),
getConnection: jest.fn().mockReturnValue(dbConn)
};
images = new Images(db);
});
describe('upload', () => {
it('should upload an image and return the inserted ID', async () => {
const testFile = { originalname: 'test.png', buffer: Buffer.from('dummydata'), mimetype: 'image/png' };
const userId = 'user123';
const result = await images.upload(testFile, userId);
expect(db.connect).toHaveBeenCalled();
expect(db.getConnection).toHaveBeenCalled();
expect(dbConn.collection).toHaveBeenCalledWith('images');
expect(mockImagesCollection.insertOne).toHaveBeenCalledWith({
userId: userId,
file_name: 'test.png',
file_content: testFile.buffer.toString('base64'),
mime_type: 'image/png',
created_at: expect.any(Date)
});
expect(result).toBe('image123');
});
});
describe('get', () => {
it('should retrieve the image if found', async () => {
const imageId = '65d9a8f9b5e8d1a5e6a8c9f0';
const testImage = {
file_name: 'test.png',
file_content: Buffer.from('dummydata').toString('base64'),
mime_type: 'image/png'
};
mockImagesCollection.findOne.mockResolvedValue(testImage);
const result = await images.get(imageId);
expect(db.connect).toHaveBeenCalled();
expect(db.getConnection).toHaveBeenCalled();
expect(dbConn.collection).toHaveBeenCalledWith('images');
expect(mockImagesCollection.findOne).toHaveBeenCalledWith({ _id: ObjectId.createFromHexString(imageId) });
expect(result).toEqual({
file_name: 'test.png',
file_content: Buffer.from('dummydata'),
mime_type: 'image/png'
});
});
it('should return null if image is not found', async () => {
const imageId = '65d9a8f9b5e8d1a5e6a8c9f0';
mockImagesCollection.findOne.mockResolvedValue(null);
const result = await images.get(imageId);
expect(result).toBeNull();
});
});
2025-03-10 19:03:58 -04:00
describe('getImages', () => {
2025-02-24 20:26:30 -05:00
it('should retrieve a paginated list of images', async () => {
const mockImages = [
2025-03-10 19:03:58 -04:00
{ _id: '1', userId: 'user1', file_name: 'image1.png', file_content: Buffer.from('data1'), mime_type: 'image/png' },
{ _id: '2', userId: 'user2', file_name: 'image2.png', file_content: Buffer.from('data2'), mime_type: 'image/png' }
2025-02-24 20:26:30 -05:00
];
2025-03-10 19:03:58 -04:00
mockImagesCollection.countDocuments.mockResolvedValue(2);
2025-03-14 01:56:53 -04:00
// Create a mock cursor for images collection
const mockFindCursor = {
sort: jest.fn().mockReturnThis(),
skip: jest.fn().mockReturnThis(),
limit: jest.fn().mockReturnThis(),
toArray: jest.fn().mockResolvedValue(mockImages), // Return mock images when toArray is called
};
2025-03-10 19:03:58 -04:00
2025-03-14 01:56:53 -04:00
// Mock the find method to return the mock cursor
mockImagesCollection.find.mockReturnValue(mockFindCursor);
2025-03-10 19:03:58 -04:00
const result = await images.getImages(1, 10);
2025-02-24 20:26:30 -05:00
expect(db.connect).toHaveBeenCalled();
expect(db.getConnection).toHaveBeenCalled();
expect(dbConn.collection).toHaveBeenCalledWith('images');
expect(mockImagesCollection.find).toHaveBeenCalledWith({});
2025-03-10 19:03:58 -04:00
expect(mockFindCursor.sort).toHaveBeenCalledWith({ created_at: 1 });
expect(mockFindCursor.skip).toHaveBeenCalledWith(0);
expect(mockFindCursor.limit).toHaveBeenCalledWith(10);
expect(result).toEqual({
images: [
{ id: '1', user: 'user1', file_name: 'image1.png', file_content: 'ZGF0YTE=', mime_type: 'image/png' },
{ id: '2', user: 'user2', file_name: 'image2.png', file_content: 'ZGF0YTI=', mime_type: 'image/png' }
],
total: 2,
});
2025-02-24 20:26:30 -05:00
});
2025-03-10 19:03:58 -04:00
it('should return an empty array if no images are found', async () => {
mockImagesCollection.countDocuments.mockResolvedValue(0);
const result = await images.getImages(1, 10);
expect(result).toEqual({ images: [], total: 0 });
2025-02-24 20:26:30 -05:00
});
});
2025-03-11 23:15:59 -04:00
describe('getUserImages', () => {
it('should return empty images array when no images exist', async () => {
mockImagesCollection.countDocuments.mockResolvedValue(0);
const result = await images.getUserImages(1, 10, 'user123');
expect(result).toEqual({ images: [], total: 0 });
expect(db.connect).toHaveBeenCalled();
expect(mockImagesCollection.countDocuments).toHaveBeenCalledWith({ userId: 'user123' });
});
it('should return images when they exist', async () => {
const mockImages = [
{
_id: 'img1',
userId: 'user123',
file_name: 'image1.png',
file_content: Buffer.from('testdata'),
mime_type: 'image/png'
}
];
mockImagesCollection.countDocuments.mockResolvedValue(1);
mockImagesCollection.find.mockReturnValue({
sort: jest.fn().mockReturnThis(),
skip: jest.fn().mockReturnThis(),
limit: jest.fn().mockReturnThis(),
toArray: jest.fn().mockResolvedValue(mockImages)
});
const result = await images.getUserImages(1, 10, 'user123');
expect(result).toEqual({
images: [
{
id: 'img1',
user: 'user123',
file_name: 'image1.png',
file_content: Buffer.from('testdata').toString('base64'),
mime_type: 'image/png'
}
],
total: 1
});
expect(db.connect).toHaveBeenCalled();
expect(mockImagesCollection.countDocuments).toHaveBeenCalledWith({ userId: 'user123' });
});
});
2025-03-13 18:02:26 -04:00
describe('delete', () => {
2025-03-14 01:56:53 -04:00
it('should not delete the image when it exists in the files collection', async () => {
2025-03-13 18:02:26 -04:00
const uid = 'user123';
2025-03-14 01:56:53 -04:00
const imgId = '507f191e810c19729de860ea'; // A valid 24-character ObjectId string
// Mock the files collection cursor to simulate an image found
const mockFilesCursor = {
toArray: jest.fn().mockResolvedValue([{ _id: imgId }]) // Image found
};
mockFilesCollection.find.mockReturnValue(mockFilesCursor);
mockImagesCollection.deleteOne.mockResolvedValue({ deletedCount: 0 });
2025-03-13 18:02:26 -04:00
const result = await images.delete(uid, imgId);
2025-03-14 01:56:53 -04:00
// Ensure the files collection is queried
expect(dbConn.collection).toHaveBeenCalledWith('files');
expect(mockFilesCollection.find).toHaveBeenCalledWith({
2025-03-13 18:02:26 -04:00
userId: uid,
content: { $regex: new RegExp(`/api/image/get/${imgId}`) },
});
2025-03-14 01:56:53 -04:00
// Ensure the images collection is queried for deletion
expect(dbConn.collection).toHaveBeenCalledWith('files');
expect(mockImagesCollection.deleteOne).not.toHaveBeenCalledWith({
_id: ObjectId.createFromHexString(imgId), // Ensure the ObjectId is created correctly
});
expect(result).toEqual({ deleted: false });
2025-03-13 18:02:26 -04:00
});
2025-03-14 01:56:53 -04:00
it('should delete the image if not found in the files collection', async () => {
2025-03-13 18:02:26 -04:00
const uid = 'user123';
2025-03-14 01:56:53 -04:00
const imgId = '507f191e810c19729de860ea';
// Mock the files collection cursor to simulate the image not being found
const mockFindCursor = {
toArray: jest.fn().mockResolvedValue([]) // Empty array means image not found
};
mockFilesCollection.find.mockReturnValue(mockFindCursor);
mockImagesCollection.deleteOne.mockResolvedValue({ deletedCount: 1 });
2025-03-13 18:02:26 -04:00
const result = await images.delete(uid, imgId);
2025-03-14 01:56:53 -04:00
// Ensure the deleteOne is not called if the image is not found
2025-03-13 18:02:26 -04:00
expect(mockImagesCollection.deleteOne).toHaveBeenCalled();
2025-03-14 01:56:53 -04:00
expect(result).toEqual({ deleted: true });
2025-03-13 18:02:26 -04:00
});
2025-03-14 01:56:53 -04:00
it('should return false if the delete operation fails in the images collection', async () => {
2025-03-13 18:02:26 -04:00
const uid = 'user123';
2025-03-14 01:56:53 -04:00
const imgId = '507f191e810c19729de860ea';
// Mock the files collection cursor to simulate the image being found
const mockFindCursor = {
toArray: jest.fn().mockResolvedValue([{ _id: imgId }]) // Image found
};
mockFilesCollection.find.mockReturnValue(mockFindCursor);
mockImagesCollection.deleteOne.mockResolvedValue({ deletedCount: 0 }); // Simulate failure
2025-03-13 18:02:26 -04:00
const result = await images.delete(uid, imgId);
2025-03-14 01:56:53 -04:00
// Ensure the images collection deletion is called
expect(mockImagesCollection.deleteOne).not.toHaveBeenCalledWith({
_id: ObjectId.createFromHexString(imgId), // Ensure the ObjectId is created correctly
2025-03-13 18:02:26 -04:00
});
2025-03-14 01:56:53 -04:00
2025-03-13 18:02:26 -04:00
expect(result).toEqual({ deleted: false });
});
2025-03-14 01:56:53 -04:00
2025-03-13 18:02:26 -04:00
});
2025-02-24 20:26:30 -05:00
});