typescript - 在 Jest TypeScript 中找不到名称“它”
问题描述
我尝试在 React + TypeScript 中为 Jest 创建一个初始设置。我已完成初始设置并尝试检查测试是否运行。当我使用命令运行测试npm test
时,我收到以下错误:
Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`.
我已经安装了 Jest 的类型并删除了 中的类型tsconfig.json
,但我仍然遇到同样的错误。
{
"compilerOptions": {
"target": "es6",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"plugins": [{ "name": "typescript-tslint-plugin" }],
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "preserve",
"pretty": true,
"baseUrl": "src",
"types": ["jest"],
"typeRoots": ["./src/types"],
"suppressImplicitAnyIndexErrors": true
},
"include": ["src", "node_modules/@types/jest"],
"exclude": ["node_modules"]
}
`
包.json
"jest": {
"transform": {
".(ts|tsx)": "ts-jest"
},
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
"moduleFileExtensions": [
"ts",
"tsx",
"js"
]
},
"devDependencies": {
"@babel/plugin-proposal-export-default-from": "^7.2.0",
"@types/enzyme": "^3.9.3",
"@types/jest": "^24.0.14",
"enzyme": "^3.10.0",
"gh-pages": "^1.2.0",
"husky": "^2.2.0",
"jest": "^24.8.0",
"node-sass": "^4.11.0",
"prettier": "^1.17.0",
"react-scripts": "2.1.8",
"react-test-renderer": "^16.8.6",
"stylelint": "^9.3.0",
"stylelint-config-recommended-scss": "^3.2.0",
"stylelint-config-standard": "^18.2.0",
"stylelint-order": "^0.8.1",
"stylelint-scss": "^3.1.3",
"ts-jest": "^24.0.2",
"tslint": "^5.16.0",
"tslint-config-prettier": "^1.18.0",
"tslint-plugin-prettier": "^2.0.1",
"tslint-react": "^4.0.0",
"tslint-react-hooks": "^2.1.0"
}
解决方案
安装
npm install jest @types/jest ts-jest
jest.config.js -- 在根目录
module.exports = {
roots: ['<rootDir>/src'],
transform: {
'^.+\\.tsx?$': 'ts-jest',
},
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
}
tsconfig.json
{
"compilerOptions": {
...
"types": ["reflect-metadata", "jest"],
"typeRoots": ["./types", "./node_modules/@types"]
...
},
"exclude": ["node_modules", "**/*.spec.ts", "**/*.test.ts"],
"include": ["./src/**/*.tsx", "./src/**/*.ts"]
}
推荐阅读
- javascript - 将数组数值反向保存在另一个数组中,然后将结果作为数值存储在变量中
- microsoft-graph-api - Microsoft Graph Webhook - 订阅用户组成员资格
- python - 如何在 web3py 中使用 AsyncHTTPProvider?
- ios - 重用单元格时 UITableViewCell 内容移动
- javascript - 导航栏位置固定禁用其中的所有元素
- reactjs - 你能用解构复制反应状态吗?
- python - 数据集中缺少像素……与否?
- java - JavaFx 和 MariaDB 项目不使用 Gluon 的 GraalVM 编译本机
- python - Twilio 从 python 发起呼叫并说话
- java - java上图像的宽度和高度属性问题