簡體   English   中英

開玩笑:ReferenceError:未定義全局

[英]Jest: ReferenceError: global is not defined

所以我在 Jest 上使用“react-testing-library”編寫單元測試,我有這個錯誤:

 Test suite failed to run

    ReferenceError: global is not defined

      at Object.<anonymous> (node_modules/@jest/core/node_modules/graceful-fs/graceful-fs.js:92:1)
      at Object.<anonymous> (node_modules/@jest/core/node_modules/expect/build/toThrowMatchers.js:10:24)
      at Object.<anonymous> (node_modules/@jest/core/node_modules/expect/build/index.js:35:48)
      at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)
      at runJest (node_modules/@jest/core/build/runJest.js:387:19)
      at _run10000 (node_modules/@jest/core/build/cli/index.js:408:7)
      at runCLI (node_modules/@jest/core/build/cli/index.js:261:3)

在我添加"jest-environment-jsdom": "^27.0.6"作為開發依賴項后,該錯誤就消失了。

我在使用帶有 jest v27.2.3 和 tsjest v27.0.5 的 angular v13 時遇到了這個問題,我的問題是 jest.config.ts 文件的配置,為我解決的問題是這個配置:

module.exports = {
  displayName: 'myApp',
  preset: '../../jest.preset.js',
  setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],
  globals: {
    'ts-jest': {
      tsconfig: '<rootDir>/tsconfig.spec.json',
      stringifyContentPathRegex: '\\.(html|svg)$'
    }
  },
  coverageDirectory: '../../coverage/apps/myapp',
  transform: {
    '^.+\\.(ts|mjs|js|html)$': 'jest-preset-angular'
  },
  transformIgnorePatterns: [
    '<rootDir>/node_modules/(?!lodash-es/.*)',
    '<rootDir>/node_modules/(?!ng2-charts/.*)',
    '^.+\\.js$'
  ],
  moduleNameMapper: {
    '^lodash-es$': 'lodash'
  },
  snapshotSerializers: [
    'jest-preset-angular/build/serializers/no-ng-attributes',
    'jest-preset-angular/build/serializers/ng-snapshot',
    'jest-preset-angular/build/serializers/html-comment'
  ]
};

或庫

module.exports = {
  displayName: 'myLib',
  preset: '../../../jest.preset.js',
  setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],
  globals: {
    'ts-jest': {
      tsconfig: '<rootDir>/tsconfig.spec.json',
      stringifyContentPathRegex: '\\.(html|svg)$'
    }
  },
  coverageDirectory: '../../../coverage/libs/...',
  transform: {
    '^.+\\.(ts|mjs|js|html)$': 'jest-preset-angular'
  },
  transformIgnorePatterns: ['node_modules/(?!.*\\.mjs$)'],
  snapshotSerializers: [
    'jest-preset-angular/build/serializers/no-ng-attributes',
    'jest-preset-angular/build/serializers/ng-snapshot',
    'jest-preset-angular/build/serializers/html-comment'
  ]
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM