Home > Back-end >  Jest error: Type error: res.status is not a funtion
Jest error: Type error: res.status is not a funtion

Time:05-05

I'm using a middleware to verify token with this code:

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

class VerifyToken {
    public verify(req: Request, res: Response, next: NextFunction) {
        try {
            const authHeader = req.headers["authorization"];
            const token = authHeader?.split(" ")[1];

            const signature = process.env.JWT_SIGNATURE;
            jwt.verify(token, signature);

            next();
        } catch (error) {
            return res.status(401).json("Acess denied");
        }
    }
}

export default new VerifyToken().verify;

I'm using Jest to test this middleware, here's the code:

import dotenv from "dotenv";
import { NextFunction, Request, Response } from "express";
import verifyToken from "../../src/middlewares/verifyToken";

describe("Verify token", () => {
    let mockRequest: Partial<Request>;
    let mockResponse: Partial<Response>;
    let nextFunction: NextFunction = jest.fn();

    beforeAll(() => {
        dotenv.config({ path: ".env" });
    });

    beforeEach(() => {
        mockRequest = {};
        mockResponse = {
            json: jest.fn(),
        };
    });

    it("should verify token with a invalid token", () => {
        const token = process.env.TEST_FALSE_TOKEN;

        mockRequest = {
            headers: {
                authorization: `bearer ${token}`,
            },
        };

        verifyToken(mockRequest as Request, mockResponse as Response, nextFunction);

        expect(mockResponse.status).toBe(401);
    });

    it("should verify token with a valid token", () => {
        const token = process.env.TEST_TOKEN;

        mockRequest = {
            headers: {
                authorization: `bearer ${token}`,
            },
        };

        verifyToken(mockRequest as Request, mockResponse as Response, nextFunction);

        expect(nextFunction).toBeCalledTimes(1);
    });
});

When i run a test using Jest, he show the following error:

TypeError: res.status is not a function

I've already tried to use ErrorRequestHandler with the request but happens the same error.

How can i fix this? Thanks for the help.

CodePudding user response:

Your mocked response doesn't have a status function on it..

mockResponse = {
  json: jest.fn(),
  status: jest.fn().mockReturnThis(),
};
  • Related