Jest with angular unable to turn on coverage because of es6

Viewed 178

I'm trying to set up an angular project to work with jest. So far it works with the following config

// jest.config.js
module.exports = {
  // other stuff
  preset: "jest-preset-angular",
  setupFilesAfterEnv: ["<rootDir>/setup-jest.ts"],
  globalSetup: "jest-preset-angular/global-setup",
  globals: {
    "ts-jest": {
      tsconfig: "<rootDir>/tsconfig.spec.json",
      stringifyContentPathRegex: "\\.html$",
      useESM: true,
    },
  },
};

And the following in my setup-jest.ts

import 'jest-preset-angular/setup-jest';
import './jest-global-mocks';

Problem is that as soon as I introduce any code that brings in an ES module, it blows up (even though I've tried following the ESM support page on the jest-preset-angular docs). So far, I've just dealt with this by finding alternative packages. But when I try to turn on --coverage, I get this.

 import { __decorate } from "tslib";
    ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      1 | import { TestBed } from '@angular/core/testing';
    > 2 | import { AppModule } from './app.module';
        | ^
      3 | import { APP_BASE_HREF } from '@angular/common';
      4 |
      5 | describe('The app module', () => {

I've tried dissecting jest-preset-angular and extracting the settings that seem like they should apply to projects using ES6, which has led me to making these changes:

// jest.config.js
module.exports = {
  // other stuff
  setupFilesAfterEnv: ["<rootDir>/setup-jest.ts"],
  transformIgnorePatterns: ["/node_modules/(?!tslib)"],
  transform: {
    "^.+\\.(ts|html|svg)$": "jest-preset-angular",
  },
  extensionsToTreatAsEsm: [".ts"],
  globals: {
    "ts-jest": {
      tsconfig: "<rootDir>/tsconfig.spec.json",
      stringifyContentPathRegex: "\\.html$",
      useESM: true,
    },
  },
};

And now its failing on the core angular mjs files

/Users/benwainwright1/repos/ng-budget/node_modules/@testing-library/angular/fesm2020/testing-library-angular.mjs:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import * as i0 from '@angular/core';
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

This is even more confusing for me because as far as I can see

  • the transform key doesn't specify .mjs, so .mjs files should be left alone
  • I'm using node v16 and jest v28, which should automatically treat .mjs files as modules
0 Answers
Related