No overload matches this call typescript nodejs

Viewed 770

i want to make a test that some addUser() method have been called and returned value. But i get this error: "No overload matches this call. Overload 1 of 4, '(object: typeof UserController, method: never): SpyInstance<never, never>', gave the following error.

So my userController.spec.ts where the error is in jest.spyOn(...):

import {UserController} from "../../src/modules/Users/Infrastructure/http/controllers";

describe('Users Controllers series ', function () {
    it("should create a new user", async () => {

        const spy = jest.spyOn(UserController, "addUser").mockReturnValueOnce()
    })
});

and then userController.ts here

import { UserServices} from "../../../domain/services";
import {CreateUSerDTO} from "../../../domain/dto/createUserDTO";
import express from "express";
import { Response} from "../../../../../shared/helpers/response";

export class UserController {


    constructor(private readonly userService: UserServices) {}

     async addUser(req: express.Request, res: express.Response):Promise<Response<CreateUSerDTO>> {
        let dto:CreateUSerDTO = req.body as CreateUSerDTO
        dto = {
            username:dto.username,
            useremail: dto.useremail,
            password: dto.password
        }
        try {
             const result = await this.userService.createUser(dto)
            console.log(res.json(result))
            return Response.ok<CreateUSerDTO>(result)

        }catch (error) {
           return Response.fail<CreateUSerDTO>(error)
        }
    }
}

Let me know what's wrong in my code

1 Answers

Root cause of the issue is that you are configuring the spy on the UserController constructor while addUser is only available on UserController instances.

You should either spy on the concrete UserController instance or spy on the UserController prototype:

describe('Users Controllers series ', function () {
    it("should create a new user", async () => {

        const spy = jest.spyOn(UserController.prototype, "addUser").mockReturnValueOnce()
    })
});

Related