Jest 和 TypeScript:VS Code 找不到名称

问题描述 投票:0回答:3

我正在将 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
目录是分开的。我遵循了互联网上找到的配置,但它没有改变任何东西,我错过了什么?到目前为止唯一的方法是将我的
tests
文件夹包含在
include
中的
tsconfig
设置中,这很糟糕,因为它是构建在
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'],
}
typescript visual-studio-code jestjs tsconfig ts-jest
3个回答
3
投票

只需将

jest
作为
typeAcquisition
包含在您的
tsconfig.json
中,例如:

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

2
投票

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


0
投票

我有同样的问题并添加

{
  "compilerOptions: {
    ...
    "types": ["jest"],
    ...
  },
  "include": ["src/**/*"]
}

还不够,我还要补充

{
  "compilerOptions": { ... },
  "include": ["src/**/*", "test/**/*"]
}
© www.soinside.com 2019 - 2024. All rights reserved.