Jest & TypeScript:VS Code 找不到名字



我正在使用带有TypeScript的Jest。尽管我的代码是有效的,而且我可以构建我的项目,但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)

我有分开的srctests目录。我遵循了互联网上的配置,但它没有改变任何东西,我缺少什么?到目前为止,唯一的方法是将我的tests文件夹包含在tsconfiginclude设置中,这很糟糕,因为它是在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'],
}

只需将jest作为typeAcquisition包含在tsconfig.json中即可,如:

// tsconfig.json
{
"compilerOptions": { /* ... */ },
"typeAcquisition": { "include": ["jest"] },
// ... your other options go here
}

我也有同样的问题。我找到了解决方案——在项目的根目录中打开它,而不是在父目录中。或者,您可以使用项目创建一个工作区。

最新更新