typescript 测试节点的API时出现expect(jest.fn()).toHaveBeenCalledWith(...预期错误)错误

izj3ouym  于 2022-11-26  发布在  TypeScript
关注(0)|答案(1)|浏览(204)

我是NodeJS的TDD初学者。我正在尝试为我的控制器编写一个单元测试。下面是我的单元测试-

import { Request, Response, NextFunction } from "express"
import { Credit } from "./credit.controller"

let response: any = {}
let request : any = {}
const mockResponse = () => {
    response.status = jest.fn().mockReturnValue(response)
    response.send = jest.fn().mockReturnValue(response)

    return response
}
const mockRequest = () => {
    request.query = { userType: "xy", customerNumber : "42324242" }
    return request
}
let next: NextFunction = jest.fn();

describe("Get credit details", () => {
    it("should return 200 response", async () => {
        let req = mockRequest()
        let res = mockResponse()
        await Credit(req as Request, res as Response, next)
        expect(res.status).toBeCalledWith(200)
    })
})

这是在实际控制器内部调用的响应函数-

export const sendingFinalSuccessRepsonse = (res: Response, next: NextFunction, data: interfaces.SuccessStruct) => {
    try {
        console.log("data", data)
        if (data.statusCode === 201) {
            res.status(201).send({ Message: "Document Created Succesfully" })
        } else if (data.statusCode === 200) {
            res.status(200).send(data)
        }
    } catch (error) {
        next(error)
    }
}

我的信贷控制员.ts

const Credit = async(req : Request, res: Response, next: NextFunction) => {
        try {
            const data= await axios.get("some URL")
sendingFinalSuccessRepsonse(res, next, data)

        } catch (error) {
            next(error)
        }
    }

这是我得到的错误-

expect(jest.fn()).toBeCalledWith(...expected)

    Expected: 200

    Number of calls: 0

我已经研究了很多,但真的不知道这个错误的原因。任何形式的帮助是感谢!!

pod7payv

pod7payv1#

好了,这里的问题是关于expect函数的。正如我嘲笑我的响应一样,jest我认为创建了它的一个示例,所以它应该是res.status.mock.instances[0].status而不是直接调用res.status

相关问题