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

IntelliJ无法识别Jest自定义匹配器toHaveSameText的问题排查

解决Vitest自定义匹配器在IntelliJ中类型报错的问题

问题场景

自定义了toHaveSameText匹配器,命令行和IntelliJ运行测试均正常,但编辑器中该匹配器标红,编译报错:

TS2339: Property toHaveSameText does not exist on type Assertion

相关文件如下:

原setup.d.ts

type OwnMatcher<Params extends unknown[]> = (
    this: jest.MatcherContext,
    actual: unknown,
    ...params: Params
) => jest.CustomMatcherResult

//@ts-ignore
declare global {
  namespace jest {
    interface Matchers<R, T> {
      toHaveSameText(actual: string, expected: string): T
    }
    interface ExpectExtendMap {
      toHaveSameText: OwnMatcher<[actual: string, expected: string]>
    }
  }
}

setup.js

import { expect, afterEach } from 'vitest';
import { Assertion, assert } from 'chai';
import { cleanup } from '@testing-library/react';

expect.extend({ toHaveSameText(actual, expected) {
    let test = new Assertion(actual, expected, assert.equal, true);
    test.assert(actual.replace(/\s/g, '') === expected.replace(/\s/g, ''),
        'expected #{this} to equal #{exp}',
        'expected #{this} to not equal #{act}',
        expected,
        actual,
        true);
    return { pass: true };
  }
});

afterEach(() => {
  cleanup();
});

已配置vite.config.js的setupFiles,并在tsconfig.json中添加了setup.d.ts的路径,但问题未解决。

问题原因

类型声明文件错误扩展了Jest的Matchers接口,但项目实际使用的是Vitest,两者类型体系不兼容;同时匹配器的类型签名不符合Vitest的使用逻辑(expect(actual).toHaveSameText(expected)中,actual是expect的入参,匹配器仅需接收expected)。

解决方案

1. 修正类型声明文件(setup.d.ts)

替换Jest类型为Vitest对应的类型接口:

import type { Assertion, ExpectStatic } from 'vitest'

// 定义匹配器的类型结构
type OwnMatcher<Params extends unknown[]> = (
    actual: unknown,
    ...params: Params
) => { pass: boolean; message?: () => string }

// 扩展Vitest的类型
declare module 'vitest' {
  // 给Assertion添加匹配器方法(对应expect(xxx).toHaveSameText()的使用场景)
  interface Assertion<T = any> {
    toHaveSameText(expected: string): T
  }

  // 给expect.extend定义匹配器的类型
  interface ExpectStatic {
    toHaveSameText: OwnMatcher<[expected: string]>
  }
}

2. 确保TS配置正确识别类型文件

检查tsconfig.json,确保包含类型文件并引入Vitest全局类型:

{
  "compilerOptions": {
    // 其他原有配置
    "types": ["vitest/globals"]
  },
  "include": [
    "src/**/*",
    "test/**/*",
    "./test/setup.d.ts"
  ]
}

3. 重启IntelliJ的TypeScript服务

做完上述修改后,通过File → Invalidate Caches...重启IDE的缓存和TS服务,确保类型定义被正确加载。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 02:07:36