【发布时间】:2021-01-26 16:40:16
【问题描述】:
我正在使用 Jest 和 TypeScript。尽管我的代码可以工作并且我可以构建我的项目,但 Visual Studio Code 对所有 Jest 方法都会抛出该错误(describe()、test()...):
Cannot find name 'describe'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`.ts(2582)
我有 src 和 tests 分开的目录。我遵循了在 Internet 上找到的配置,但它并没有改变任何东西,我错过了什么?到目前为止,唯一的方法是将我的tests 文件夹包含在tsconfig 的include 设置中,这很糟糕,因为它内置在dist 目录中。
已安装开发依赖项:jest ts-jest @types/jest
tsconfig.json
{
"compilerOptions": {
"sourceMap": true,
"module": "commonjs",
"moduleResolution": "node",
"esModuleInterop": true,
"allowJs": true,
"jsx": "react",
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"baseUrl": "./",
"paths": {
"*": ["src/*"]
},
"typeRoots": ["./node_modules/@types"],
"types": ["node", "jest"]
},
"strict": true,
"compileOnSave": false,
"include": ["src"]
}
jest.config.js
module.exports = {
roots: ['<rootDir>'],
preset: 'ts-jest',
testRegex: 'tests/src/.*\\.test.(js|jsx|ts|tsx)$',
transform: {
'^.+\\.tsx?$': 'ts-jest',
},
transformIgnorePatterns: [],
snapshotSerializers: ['enzyme-to-json/serializer'],
moduleDirectories: ['node_modules', 'src', 'tests'],
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
moduleNameMapper: {
'\\.(css|scss|jpg|png|svg)$': 'mocks/empty.ts',
},
setupFilesAfterEnv: ['<rootDir>/tests/jest.setup.ts'],
collectCoverage: true,
collectCoverageFrom: ['src/**/*.{js{,x},ts{,x}}', '!src/index.tsx', '!src/custom.d.ts'],
}
【问题讨论】:
-
我认为问题不在于您的
tsconfig.json文件,您不应该在那里做任何事情,不确定您的jest.config.js文件,但您是否尝试过使用 @ 开发测试987654338@,如果可以,您可以使用导入语句发布该代码吗?另外,你在终端运行什么来运行测试?请记住,Jest 没有开箱即用的 TypeScript 知识,即使使用jest和ts-jest也会出现问题。 -
请看类似问题的答案:stackoverflow.com/a/61153019/3082178。
标签: typescript visual-studio-code jestjs tsconfig ts-jest