React+TypeScript项目中Jest与Cypress类型冲突问题求助
React+TypeScript项目中Cypress与Jest类型冲突问题解决
问题现象
安装Cypress后执行yarn check-type,单元测试文件(如test/unit/vmr.test.ts)出现类型错误:
test/unit/vmr.test.ts:53:18 - error TS2551: Property 'toEqual' does not exist on type 'Assertion'. Did you mean 'equal'? 53 expect(rows).toEqual( ~~~~~~~ node_modules/cypress/types/chai/index.d.ts:206:9 206 equal: Equal; ~~~~~ 'equal' is declared here.
问题根源
主tsconfig.json的include规则覆盖了所有.ts文件(包括单元测试文件),同时Cypress的Chai类型定义被全局引入,导致TypeScript处理单元测试时,错误将Jest的expect断言识别为Cypress的Chai断言类型(后者仅提供equal方法,无toEqual)。
解决方案
方案1:拆分单元测试与Cypress的TypeScript配置
- 为单元测试单独创建
tsconfig.test.json:
{ "extends": "./tsconfig.json", "compilerOptions": { "types": ["jest", "@types/testing-library__jest-dom"] }, "include": [ "test/unit/**/*.test.ts", "next-env.d.ts", "**/*.ts", "**/*.tsx" ], "exclude": [ "node_modules", "cypress/**/*", "**/*.spec.ts" ] }
- 修改主
tsconfig.json的exclude规则,排除单元测试文件:
"exclude": [ "node_modules", "**/*.spec.ts", "test/unit/**/*.test.ts" ]
- 更新
package.json中的类型检查命令,同时验证主配置和测试配置:
"scripts": { "check-type": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json" }
方案2:修复Cypress的tsconfig配置
调整cypress/tsconfig.json,避免继承主配置时引入Jest类型,同时限制Cypress类型仅作用于自身目录:
{ "compilerOptions": { "target": "es5", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": true, "forceConsistentCasingInFileNames": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "baseUrl": "..", "paths": { "~/*": ["./*"], "*": ["types/*"] }, "types": ["cypress"] }, "include": [ "./**/*.ts", "../cypress.config.ts" ], "exclude": [ "../node_modules", "../test/**/*" ] }
方案3:在单元测试文件中显式指定Jest类型
在每个单元测试文件顶部添加类型引用注释,强制TypeScript使用Jest断言类型:
/// <reference types="jest" /> /// <reference types="@types/testing-library__jest-dom" />
验证
执行yarn check-type,确认类型错误消失。
内容的提问来源于stack exchange,提问作者Jonathan Batey
相关产品推荐
相关产品推荐

