简体   繁体   中英

Jest: ReferenceError: global is not defined

So I am writing unit test using "react-testing-library" on Jest and I have this error:

 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"作为开发依赖项后,该错误就消失了。

I had this problem using angular v13 with jest v27.2.3 and tsjest v27.0.5 and my problem was with the configuration of jest.config.ts files and what solves it for me was this configuration:

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'
  ]
};

or to libs

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'
  ]
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM