【问题标题】:Jest error: Type error: res.status is not a function开玩笑错误:类型错误:res.status 不是函数
【发布时间】:2022-11-09 21:50:14
【问题描述】:

我正在使用中间件通过以下代码验证令牌:

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;

我正在使用 Jest 来测试这个中间件,代码如下:

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);
    });
});

当我使用 Jest 运行测试时,它显示以下错误:

TypeError: res.status is not a function

我已经尝试将 ErrorRequestHandler 与请求一起使用,但我得到了同样的错误。

我怎样才能解决这个问题?谢谢您的帮助。

【问题讨论】:

    标签: node.js typescript express middleware ts-jest


    【解决方案1】:

    您的模拟响应没有 status 函数。

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

    【讨论】:

    • 谢谢您的帮助!添加状态函数,我得到另一个错误,当期望状态代码 401 他收到一个 [Function mockConstructor]
    • 你应该改用expect(mockResponse.status).toHaveBeenCalledWith(401)
    • @izakVoigt np,请勾选正确答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 2021-09-27
    • 1970-01-01
    • 2020-04-26
    • 1970-01-01
    • 2021-02-26
    相关资源
    最近更新 更多