使用CRA+TypeScript+Jest时出现toMatchSnapshot类型错误求助
解决Jest快照测试中
Property 'toMatchSnapshot' does not exist on type 'Assertion'错误 修复步骤
1. 确保Jest类型定义被正确识别
要么在每个测试文件顶部手动引入Jest类型:
import '@types/jest';
要么在tsconfig.json的compilerOptions里统一配置类型包含:
{ "compilerOptions": { "types": ["jest"] } }
2. 卸载手动安装的Jest依赖,改用CRA内置版本
你当前手动安装了jest、ts-jest等包,但CRA本身已经集成了适配好的Jest环境,版本冲突是大概率诱因:
npm uninstall jest ts-jest @types/jest jest-environment-jsdom
同时删掉package.json里自定义的jest配置块,CRA会自动处理Jest的各项配置。
3. 处理tree的空值类型问题
renderer.create().toJSON()返回的类型可能是null,可以加非空断言或者类型守卫避免TypeScript报错:
// 非空断言 expect(tree!).toMatchSnapshot(); // 或者类型守卫 if (tree) { expect(tree).toMatchSnapshot(); }
4. 清除缓存并重装依赖
# 清除Jest缓存 npx jest --clearCache # 重装依赖 rm -rf node_modules package-lock.json npm install
内容的提问来源于stack exchange,提问作者Benji
相关产品推荐
相关产品推荐

