Unable to mock routes with Prisma and Jest

56 Views Asked by At

I'm writing a test for an authenticated /POST route using the Jest library. I've tested the route manually in Insomnia and I'm able to successfully send a POST request. However, when writing the test, I get an 500 status code. Upon closer inspection in the console, this error appears also:

console.error
    PrismaClientKnownRequestError: 
    Invalid `prisma.board.create()` invocation in
    /Users/[username]/Coding/projects/[project_name]/server/controllers/boards.ts:17:49
    
      14 
      15 console.log("USER ID: ", userId)
      16 
    → 17 const createdBoard = await prisma.board.create(
    An operation failed because it depends on one or more records that were required but not found. Expected 1 records to be connected, found only 0.
        at si.handleRequestError (/Users/[username]/Coding/projects/[projectname]/server/node_modules/@prisma/client/runtime/library.js:125:6817)

Here is the route:

boardsRouter.post("/", authenticateUser, async (request: Request, response: Response) => {
    try {
        const { name, userId } = request.body
        if (!name) {
            return response.status(400).json({ error: 'Board name is required' });
        }

        console.log("USER ID: ", userId)

        const createdBoard = await prisma.board.create({
        data: {
            name,
            members: {
            connect: { id: userId },
            },
        },
    });

        return response.status(201).json(createdBoard);
    } catch (error) {
        console.error(error)
        return response.status(500).json({ error: 'Internal Server Error' });
    }
})

export default boardsRouter;

authenticateUser middleware:

import { Request, Response, NextFunction } from 'express';
import jwt, { JwtPayload } from 'jsonwebtoken';

export const authenticateUser = (req: Request, res: Response, next: NextFunction) => {
  const token = (req.headers as { authorization?: string }).authorization?.replace('Bearer ', '');

  console.log('Received token:', token);
  if (!token) {
    return res.status(401).json({ error: 'Unauthorized - Missing token' });
  }
  console.log("secret key: ", process.env.SECRET)
  try {
    const decoded = jwt.verify(token, process.env.SECRET || '');
    console.log("DECODED: ", decoded)
    if (typeof decoded === 'string') {
      throw new Error('Invalid token');
    }

    // Attach user information to the request for later use
    req.body.userId = decoded.id;
    next();
  } catch (error) {
    res.status(401).json({ error: 'Unauthorized - Invalid token' });
  }
};

Here's the accompanying test:

import supertest from "supertest";
import app from "../index";
import { prismaMock } from "../prisma/singleton";
import jwt from 'jsonwebtoken';

const api = supertest(app);

const mockJwt = (payload: any): string => {
  const secret = process.env.SECRET || "";
  return jwt.sign(payload, secret);
};

beforeAll(async () => {
  await prismaMock.$connect();
});

afterAll(async () => {
  await prismaMock.$disconnect();
});

test("should create a new board when a valid request is made", async () => {
    // Mock user data and token
    const userId = '123456789';
    const token = mockJwt({ id: userId });

    prismaMock.user.create.mockResolvedValue({
        id: userId,
        name: "Test User",
        username: "test user",
        email: "[email protected]",
        password: "password"
    });

    // Mock request body
    const boardData = {
      name: "Test Board",
      userId,
    };



    // Mock Prisma behavior
    prismaMock.board.create.mockResolvedValue({
      id: 'board123',
      name: "Test Board",
      createdAt: new Date(),
      updatedAt: new Date(),
      deletedAt: null,
    });

    // Send request
    const response = await api
      .post("/api/boards")
      .set("Authorization", `Bearer ${token}`)
      .send(boardData);

    // Assertions
    expect(response.status).toBe(201);
  });

Any suggestions on how to effectively test this route? Not sure what the issue is here since I'm sending a user id. Thank you.

0

There are 0 best solutions below