Search code examples
node.jstypescriptjestjsts-jest

expect(jest.fn()).toHaveBeenCalledWith(...expected) error in testing nodejs api


I am a beginner in TDD with NodeJS. And I am trying to write a unit test for my controller. Here is my unit test -

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

Here is my response function which is called inside the actual controller -

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

My creditcontroller.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)
        }
    } 

And here is the error I am getting -

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

    Expected: 200

    Number of calls: 0

I have researched a lot, but really don't know the reason of this error. Any kind of help is appreciated!!


Solution

  • Okay so issue here was with the expect function. As I had mocked my response, jest I think creates an instance of it so instead of directly calling the res.status it should have been res.status.mock.instances[0].status