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

VS Code中TypeScript无法识别自定义Jest AxiosResponse匹配器问题

解决Jest自定义匹配器TypeScript类型不识别问题

问题描述

我创建了自定义Jest匹配器,用于扩展expect以处理AxiosResponse对象,命令行测试可正常运行,但VS Code中的TypeScript始终无法识别该自定义匹配器,报错:

Property 'status' does not exist on type 'JestMatchers<AxiosResponse<any, any>>'.ts(2339)

已尝试的解决方法

  • 创建jest-custom-matchers.d.ts类型声明文件:
import 'jest';

declare global {
  namespace jest {
    interface Matchers<R> {
      status(expectedStatus: number): R;
    }
  }
}
  • 配置tsconfig.json包含types目录:
{
  "compilerOptions": {
    "typeRoots": ["./node_modules/@types", "./types"],
  },
  "include": ["src/**/*", "types/**/*"]
}
  • 重启VS Code的TypeScript服务器,排查冲突类型定义
  • 将.d.ts文件移至项目根目录

可行解决方案

1. 修正类型声明文件,确保其作为模块加载

类型声明文件必须被识别为模块才能触发全局类型合并,在jest-custom-matchers.d.ts末尾添加export {},同时兼容expect模块和全局jest命名空间的扩展:

import 'jest';
import { AxiosResponse } from 'axios';

// 扩展expect模块的Matchers类型
declare module 'expect' {
  interface Matchers<R> {
    status(expectedStatus: number): R;
  }
}

// 扩展全局jest命名空间的Matchers类型
declare global {
  namespace jest {
    interface Matchers<R> {
      status(expectedStatus: number): R;
    }
  }
}

// 标记为模块,确保类型合并生效
export {};

2. 简化tsconfig.json配置(可选)

如果类型文件放在项目根目录或src下,可移除typeRoots配置(默认已包含node_modules/@types),确保include覆盖所有需要的文件:

{
  "compilerOptions": {
    // 其他编译配置...
  },
  "include": ["src/**/*", "*.d.ts"]
}

3. 切换VS Code使用项目本地TypeScript版本

VS Code默认使用内置TypeScript版本,可能与项目依赖版本不一致导致类型识别异常:

  • 点击VS Code右下角的TypeScript版本号
  • 选择「Use Workspace Version」,使用项目node_modules中的TypeScript版本

4. 确认自定义匹配器正确注册

在Jest测试启动文件(如setupTests.ts)中注册匹配器,并确保该文件被Jest加载:

import { expect } from '@jest/globals';
import { AxiosResponse } from 'axios';

expect.extend({
  status(received: AxiosResponse, expectedStatus: number) {
    const pass = received.status === expectedStatus;
    return {
      message: () => pass 
        ? `expected response status not to be ${expectedStatus}`
        : `expected response status to be ${expectedStatus} but got ${received.status}`,
      pass,
    };
  },
});

在jest.config.js中配置启动文件路径:

module.exports = {
  // 其他Jest配置...
  setupFilesAfterEnv: ['./src/setupTests.ts'],
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 07:16:06