test: Update user tests to use dynamic ObjectId and add validation for ObjectId

This commit is contained in:
StarAppeal
2025-09-30 06:55:02 +02:00
parent 9975e4f1b1
commit 329911d3b5
2 changed files with 21 additions and 3 deletions
+13
View File
@@ -1,5 +1,6 @@
import { describe, it, expect, vi } from "vitest";
import { v, validateBody, validateParams, validateQuery } from "../../../src/rest/middleware/validate";
import { Types } from "mongoose";
describe("v.isString", () => {
it("accepts a simple string", () => {
@@ -91,6 +92,18 @@ describe("v.isUrl", () => {
});
});
describe("v.isObjectId", () => {
it("accepts valid ObjectIds", () => {
expect(v.isObjectId()(new Types.ObjectId().toString())).toBe(true);
});
it("rejects invalid ObjectIds and non-strings", () => {
expect(v.isObjectId()("invalidobjectid")).toBe("must be a valid ObjectId");
expect(v.isObjectId()(123 as any)).toBe("must be a valid ObjectId");
});
});
describe("validateBody Middleware", () => {
const schema = {
name: { required: true, validator: v.isString({ nonEmpty: true }) },
+8 -3
View File
@@ -4,6 +4,7 @@ import request from "supertest";
import {RestUser} from "../../src/rest/restUser";
// @ts-ignore
import {createMockUserService, setupTestEnvironment, type TestEnvironment} from "../helpers/testSetup";
import { Types } from "mongoose";
vi.mock("../../src/services/db/UserService", () => ({
UserService: {
@@ -345,7 +346,7 @@ describe("RestUser", () => {
});
describe("GET /:id (Admin only)", () => {
const specificUserId = "66580f13f1e9e8c4b7a2d4c1";
const specificUserId = new Types.ObjectId().toString();
const mockUser = {
id: specificUserId,
name: "specificuser",
@@ -372,11 +373,15 @@ describe("RestUser", () => {
it("should return bad request when target user is not found", async () => {
mockedUserService.getUserById.mockResolvedValue(null);
const nonExistentUserId = new Types.ObjectId().toString();
const response = await request(testEnv.app)
.get(`/user/66580f13f1e9e8c4b7a2d4c2`)
.get(`/user/${nonExistentUserId}`)
.expect(400);
expect(response.body.data.message).toBe("Unable to find matching document with id: 66580f13f1e9e8c4b7a2d4c2");
expect(response.body.data.message).toBe(`Unable to find matching document with id: ${nonExistentUserId}`);
});
});