【问题标题】:No overload matches this call typescript nodejs没有重载匹配这个调用 typescript nodejs
【发布时间】:2021-12-19 12:11:21
【问题描述】:

我想测试一些 addUser() 方法已被调用并返回值。但我收到此错误:“No overload matches this call. Overload 1 of 4, '(object: typeof UserController, method: never): SpyInstance<never, never>', gave the following error.

所以我的 userController.spec.ts 错误在 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()
    })
});

然后这里是 userController.ts

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

让我知道我的代码出了什么问题

【问题讨论】:

    标签: node.js typescript unit-testing jestjs


    【解决方案1】:

    问题的根本原因是您在UserController 构造函数上配置了间谍,而addUser 仅在UserController 实例上可用。

    您应该监视具体的 UserController 实例或监视 UserController 原型:

    describe('Users Controllers series ', function () {
        it("should create a new user", async () => {
    
            const spy = jest.spyOn(UserController.prototype, "addUser").mockReturnValueOnce()
        })
    });
    
    

    【讨论】:

    • 感谢它运行良好
    • @cedric 很高兴知道它运行良好。如果解决了问题,请采纳答案。
    猜你喜欢
    • 2020-06-14
    • 1970-01-01
    • 2022-06-11
    • 2021-10-12
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    • 1970-01-01
    相关资源
    最近更新 更多