How to set up Jest in Angular?

Discussão em 'Angular' iniciado por infinitezero, Novembro 24, 2025.

  1. infinitezero

    infinitezero Guest

    I have multiple tries with different AIs and reading through guides, documentation, and Stack Overflow posts:


    It just doesn't work. I also tried to switch to Vitest but that got even worse.

    My monorepo folder structure is as follows, where lib is an Angular library and project is an Angular project:

    dist
    lib
    --library
    src
    --project

    jest.config.ts
    setup-jest.ts
    tsconfig.json
    tsconfig.spec.json


    I have installed:

    "devDependencies": {
    "@angular/build": "^20.2.1",
    "@angular/cli": "^20.0.5",
    "@angular/compiler-cli": "^20.0.0",
    "@types/jasmine": "~5.1.0",
    "@types/jest": "^30.0.0",
    "jasmine-core": "~5.7.0",
    "jest": "^30.2.0",
    "jest-environment-jsdom": "^30.2.0",
    "jest-preset-angular": "^15.0.3",
    "karma": "~6.4.0",
    "karma-chrome-launcher": "~3.2.0",
    "karma-coverage": "~2.2.0",
    "karma-jasmine": "~5.1.0",
    "karma-jasmine-html-reporter": "~2.1.0",
    "ng-packagr": "^20.2.0",
    "ts-jest": "^29.4.5",
    "ts-node": "^10.9.2",
    "typescript": "~5.8.2"
    }


    I have:

    "test": "jest",


    under scripts in my package.json.

    My setup-jest.ts file:

    import { setupZoneTestEnv } from 'jest-preset-angular/setup-env/zone';

    setupZoneTestEnv();


    My tsconfig.spec.json

    {
    "extends": "./tsconfig.json",
    "compilerOptions": {
    "target": "ES2020",
    "module": "ES2022",
    "esModuleInterop": true,
    "types": [
    "jest"
    ]
    },
    "include": [
    "src/**/*.spec.ts",
    "src/**/*.d.ts"
    ]
    }


    And finally my jest.config.ts

    import type { Config } from 'jest';
    import { createCjsPreset } from 'jest-preset-angular/presets/index.js';

    export default {
    ...createCjsPreset(),
    setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'],
    testEnvironment: "jsdom",
    testPathIgnorePatterns: [
    "node_modules",
    "dist/.*",
    ],
    modulePathIgnorePatterns: [
    "<rootDir>/dist/"
    ],
    transform: {
    "^.+\\.(ts|js|html)$": [
    "jest-preset-angular",
    {
    tsconfig: "<rootDir>/tsconfig.spec.json",
    stringifyContentPathRegex: "\\.(html|svg)$"
    }
    ]
    },
    transformIgnorePatterns: ["node_modules/(?!.*\\.mjs$)"]
    } satisfies Config;


    This all just results in:

    SyntaxError: Cannot use import statement outside a module

    > 1 | import { setupZoneTestEnv } from 'jest-preset-angular/setup-env/zone';
    | ^
    2 |
    3 | setupZoneTestEnv();

    Continue reading...

Compartilhe esta Página