You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript Node.js环境下jest.spyOn测试报No overload匹配错误如何解决

问题排查与修复方案

核心错误原因

你代码中定义的addUser是UserController类的实例方法,仅存在于类的实例对象上,并非挂载在类本身的静态方法。你测试时直接把UserController构造函数(类本身)传给jest.spyOn,试图读取不存在的静态方法addUser,因此触发了类型匹配错误。

同时还有一个隐藏问题:addUser是异步方法,返回值为Promise类型,用同步的mockReturnValueOnce传入返回值也会出现类型不匹配问题。

修复步骤

  • 先构造UserServices的mock实例,传入UserController构造函数生成类实例,避免依赖真实业务逻辑
  • 对生成的实例对象调用jest.spyOn监听addUser方法,模拟返回值时用适配异步方法的mockResolvedValueOnce
  • 补充测试执行和断言逻辑,验证方法调用符合预期

修复后的测试代码

import {UserController} from "../../src/modules/Users/Infrastructure/http/controllers";
// 导入对应依赖类型
import type { UserServices } from "../../src/modules/Users/domain/services";
import type { Response } from "../../../../../shared/helpers/response";
import type { CreateUSerDTO } from "../../src/modules/Users/domain/dto/createUserDTO";
import express from "express";

describe('Users Controllers series ', function () {
    it("should create a new user", async () => {
        // 1. mock UserServices依赖
        const mockUserService = {
            createUser: jest.fn()
        } as unknown as UserServices;
        // 2. 生成UserController实例
        const userController = new UserController(mockUserService);
        
        // 3. 构造符合返回类型的模拟值,对实例方法打桩
        const mockReturn = Response.ok<CreateUSerDTO>({
            username: 'testUser',
            useremail: 'test@example.com',
            password: 'testPwd123'
        })
        const addUserSpy = jest.spyOn(userController, "addUser").mockResolvedValueOnce(mockReturn);

        // 4. 构造模拟的请求、响应参数,调用方法
        const mockReq = {
            body: {
                username: 'testUser',
                useremail: 'test@example.com',
                password: 'testPwd123'
            }
        } as unknown as express.Request;
        const mockRes = {} as unknown as express.Response;
        await userController.addUser(mockReq, mockRes);

        // 5. 断言验证
        expect(addUserSpy).toHaveBeenCalledTimes(1);
        expect(addUserSpy).toHaveBeenCalledWith(mockReq, mockRes);
    })
});

如果你不需要修改addUser的实现逻辑,仅需要监听方法的真实调用,直接去掉mockResolvedValueOnce调用即可。

内容的提问来源于stack exchange,提问作者dollars

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 02:27:02