|
| 1 | +const { bootcampPhotoUpload } = require("../controllers/bootcampsController"); |
| 2 | +const { Bootcamp } = require("../models"); |
| 3 | +const ErrorResponse = require("../utils/ErrorResponse"); |
| 4 | + |
| 5 | +jest.mock("../models", () => ({ |
| 6 | + Bootcamp: { |
| 7 | + findById: jest.fn(), |
| 8 | + findByIdAndUpdate: jest.fn().mockResolvedValue({}), |
| 9 | + }, |
| 10 | +})); |
| 11 | + |
| 12 | +describe("Bootcamp Photo Upload File Extension Validation", () => { |
| 13 | + let req, res, next; |
| 14 | + |
| 15 | + beforeEach(() => { |
| 16 | + jest.clearAllMocks(); |
| 17 | + req = { |
| 18 | + params: { id: "60d5ec49f1b2c80015f8e001" }, |
| 19 | + user: { |
| 20 | + id: "5d7a514b5d2c12c7449be042", |
| 21 | + role: "publisher", |
| 22 | + name: "Publisher User", |
| 23 | + }, |
| 24 | + files: null, |
| 25 | + }; |
| 26 | + res = { |
| 27 | + status: jest.fn().mockReturnThis(), |
| 28 | + json: jest.fn(), |
| 29 | + }; |
| 30 | + next = jest.fn(); |
| 31 | + }); |
| 32 | + |
| 33 | + it("should reject files with invalid extensions (e.g. .php, .html, .svg) even if mimetype is image/png", async () => { |
| 34 | + Bootcamp.findById.mockResolvedValue({ |
| 35 | + _id: "60d5ec49f1b2c80015f8e001", |
| 36 | + user: { toString: () => "5d7a514b5d2c12c7449be042" }, |
| 37 | + }); |
| 38 | + |
| 39 | + req.files = { |
| 40 | + file: { |
| 41 | + name: "malicious.php", |
| 42 | + mimetype: "image/png", // Forged MIME type |
| 43 | + size: 1000, |
| 44 | + }, |
| 45 | + }; |
| 46 | + |
| 47 | + await bootcampPhotoUpload(req, res, next); |
| 48 | + |
| 49 | + expect(next).toHaveBeenCalledTimes(1); |
| 50 | + const error = next.mock.calls[0][0]; |
| 51 | + expect(error).toBeInstanceOf(ErrorResponse); |
| 52 | + expect(error.statusCode).toBe(400); |
| 53 | + expect(error.message).toContain( |
| 54 | + "Please Upload A Valid Image File Extension", |
| 55 | + ); |
| 56 | + }); |
| 57 | + |
| 58 | + it("should accept valid image extension .png", async () => { |
| 59 | + Bootcamp.findById.mockResolvedValue({ |
| 60 | + _id: "60d5ec49f1b2c80015f8e001", |
| 61 | + user: { toString: () => "5d7a514b5d2c12c7449be042" }, |
| 62 | + }); |
| 63 | + |
| 64 | + const fileMoveMock = jest.fn((dest, cb) => cb(null)); |
| 65 | + req.files = { |
| 66 | + file: { |
| 67 | + name: "test_image.png", |
| 68 | + mimetype: "image/png", |
| 69 | + size: 1000, |
| 70 | + mv: fileMoveMock, |
| 71 | + }, |
| 72 | + }; |
| 73 | + |
| 74 | + process.env.MAX_FILE_UPLOAD = "1000000"; |
| 75 | + process.env.FILE_UPLOAD_PATH = "./public/uploads"; |
| 76 | + |
| 77 | + await bootcampPhotoUpload(req, res, next); |
| 78 | + |
| 79 | + expect(next).not.toHaveBeenCalledWith(expect.any(ErrorResponse)); |
| 80 | + expect(fileMoveMock).toHaveBeenCalled(); |
| 81 | + }); |
| 82 | +}); |
0 commit comments