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

React+TypeScript配置Cypress时yarn check-type报toMatchSnapshot错误

问题场景

基于React.js、TypeScript技术栈开发的项目原有测试框架为Jest,新增配置Cypress后执行yarn check-type类型检查命令时抛出如下错误:

test/snapshot/VmrFormInternal.test.tsx:278:35 - error TS2339: Property 'toMatchSnapshot' does not exist on type 'Assertion'.

278 expect(EnzymeToJson(subject)).toMatchSnapshot();
现有配置

tsconfig.spec.json

{
    "extends": "./tsconfig.json",
    "include": [
      "**/*.spec.ts"
    ],
}

cypress.config.ts

import { defineConfig } from 'cypress';

export default defineConfig({
  e2e: {
    // implement node event listeners here
  }
});

tsconfig.lint.json

{
    "extends": "./tsconfig.json",
    "compilerOptions": {
      "noEmit": true
    },
    "exclude": []
}

tsconfig.json(核心片段)

...
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx"
  ],
  "exclude": [
    "node_modules",
    "**/*.spec.ts",
    "**/*.test.ts"
  ]
...
根因

报错的核心原因是Jest与Cypress的全局类型冲突:

  1. 根tsconfig.json的exclude规则仅排除了.spec.ts、.test.ts后缀的文件,未覆盖.test.tsx、.spec.tsx后缀的测试文件,导致这类Jest测试文件被纳入全局TS检查范围。
  2. 安装Cypress后,Cypress自带的Chai断言类型(即报错中提到的Assertion类型)被全局注入,覆盖了Jest的expect类型定义,而Chai的Assertion类型上不存在Jest专属的toMatchSnapshot方法,因此抛出类型错误。
  3. 配套的tsconfig.spec.json配置存在遗漏:include规则仅匹配.spec.ts文件,未覆盖其他后缀的Jest测试文件,也未显式指定Jest类型,无法为测试文件提供正确的类型推导。
修复步骤
  • 调整根目录tsconfig.json的exclude规则,补全所有Jest测试文件后缀,避免Cypress全局类型污染Jest测试文件:
    将原有exclude配置中的测试文件规则替换为:
    "exclude": [
      "node_modules",
      "**/*.spec.ts",
      "**/*.test.ts",
      "**/*.spec.tsx",
      "**/*.test.tsx",
      "cypress.config.ts"
    ]
    
  • 修改tsconfig.spec.json配置,覆盖所有Jest测试文件类型,显式引入Jest类型声明,确保测试文件能正确识别Jest断言方法:
    {
      "extends": "./tsconfig.json",
      "compilerOptions": {
        "types": ["jest", "node"]
      },
      "include": [
        "**/*.spec.ts",
        "**/*.test.ts",
        "**/*.spec.tsx",
        "**/*.test.tsx"
      ]
    }
    
  • (可选但推荐)为Cypress单独创建专属tsconfig配置(如tsconfig.cypress.json),隔离Cypress与Jest的类型,避免后续冲突:
    // tsconfig.cypress.json
    {
      "extends": "./tsconfig.json",
      "compilerOptions": {
        "types": ["cypress", "node"]
      },
      "include": [
        "cypress/**/*.ts",
        "cypress.config.ts"
      ]
    }
    
  • 重新执行yarn check-type命令,验证类型检查是否通过。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 14:48:21