Can't run tests in a Angular 9 project

Viewed 1160

I'm working on an Angular codebase (first time) and I want to test my components using the default test runner brought with Angular. Here, my issue is that I can't run tests, I always get an error, the same for each test:

  ● Test suite failed to run

    File not found: jest-preset-angular/InlineHtmlStripStylesTransformer.js (resolved as: /path/to/project/client/jest-preset-angular/InlineHtmlStripStylesTransformer.js)

      at ConfigSet.resolvePath (node_modules/ts-jest/dist/config/config-set.js:725:19)
      at node_modules/ts-jest/dist/config/config-set.js:250:98
          at Array.map (<anonymous>)
      at ConfigSet.get (node_modules/ts-jest/dist/config/config-set.js:250:64)
      at ConfigSet.<anonymous> (node_modules/ts-jest/dist/util/memoize.js:44:24)
      at ConfigSet.get (node_modules/ts-jest/dist/config/config-set.js:315:41)
      at ConfigSet.<anonymous> (node_modules/ts-jest/dist/util/memoize.js:44:24)
      at ConfigSet.get (node_modules/ts-jest/dist/config/config-set.js:585:32)
      at ConfigSet.<anonymous> (node_modules/ts-jest/dist/util/memoize.js:44:24)
      at ConfigSet.get (node_modules/ts-jest/dist/config/config-set.js:603:25)

note: in the original error "path/to/project" is the absolute path to the project and it is correct.

As I said every tests returns the same error as above so the final output of yarn test is:

Test Suites: 48 failed, 48 total
Tests:       0 total
Snapshots:   0 total
Time:        6.896 s
Ran all test suites.

Watch Usage: Press w to show more.

My codebase uses Angular 9:

Angular CLI: 9.1.12
Node: 10.23.2
OS: darwin x64

Angular: 9.1.12
... animations, cli, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router, service-worker
Ivy Workspace: Yes

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.901.10
@angular-devkit/build-angular     0.901.10
@angular-devkit/build-optimizer   0.901.10
@angular-devkit/build-webpack     0.901.10
@angular-devkit/core              9.1.12
@angular-devkit/schematics        9.1.12
@angular/cdk                      12.2.4
@angular/flex-layout              9.0.0-beta.31
@ngtools/webpack                  9.1.10
@schematics/angular               9.1.12
@schematics/update                0.901.12
rxjs                              6.6.0
typescript                        3.8.3
webpack                           4.42.0

It also follows the basic jest-preset-angular config example (I think):

// client/jest.config.js
module.exports = {
  preset: 'jest-preset-angular',
  roots: ['src'],
  coverageDirectory: 'reports',
  setupFilesAfterEnv: ['<rootDir>/src/setup-jest.ts'],
  moduleNameMapper: {
    '@app/(.*)': '<rootDir>/src/app/$1',
    '@env': '<rootDir>/src/environments/environment'
  },
  globals: {
    'ts-jest': {
      allowSyntheticDefaultImports: true,
      tsConfig: '<rootDir>/tsconfig.spec.json'
    }
  },
  // Do not ignore librairies such as ionic, ionic-native or bootstrap to transform them during unit testing.
  transformIgnorePatterns: ['node_modules/(?!(jest-test|@clr))']
};
// client/src/setup-jest.ts
import 'jest-preset-angular';

/* global mocks for jsdom */
const storageMock = () => {
  let storage: { [key: string]: string } = {};
  return {
    getItem: (key: string) => (key in storage ? storage[key] : null),
    setItem: (key: string, value: string) => (storage[key] = value || ''),
    removeItem: (key: string) => delete storage[key],
    clear: () => (storage = {}),
  };
};

Object.defineProperty(window, 'localStorage', { value: storageMock() });
Object.defineProperty(window, 'sessionStorage', { value: storageMock() });
Object.defineProperty(window, 'getComputedStyle', {
  value: () => ['-webkit-appearance'],
});

Object.defineProperty(document.body.style, 'transform', {
  value: () => {
    return {
      enumerable: true,
      configurable: true,
    };
  },
});

Object.defineProperty(window, 'getComputedStyle', {
  value: () => ({
    getPropertyValue: (prop: any) => {
      return '';
    },
  }),
});

Object.defineProperty(window, 'matchMedia', {
  value: (query: any) => ({
    matches: false,
    media: query,
    onchange: null as any,
    addListener: () => {},
    removeListener: () => {},
  }),
});

And my package.json has the following versions of jest-related modules:

{
    "devDependencies": {
        "jasmine-core": "^3.5.0",
        "jasmine-spec-reporter": "~5.0.2",
        "jest": "26",
        "jest-preset-angular": "^8.2.1",
        "@angular-builders/jest": "^8.3.2"
    }
}

As I said, I'm a beginner with Angular. As far as I can't understand, this error seems to come from a build error / transpilation error but I can't find any response to this problem. Has someone already experienced the same issue?

I've already tried the following things:

Angular + Jest: Can't resolve all parameters for AppComponent: (?)

https://itnext.io/how-i-do-configure-jest-to-test-my-angular-8-project-2bd84a21d725

Angular 8 and jest - File not found: jest-preset-angular/InlineHtmlStripStylesTransformer.js

https://github.com/thymikee/jest-preset-angular#exposed-configuration

EDIT

I already tried Angular 8 and jest - File not found: jest-preset-angular/InlineHtmlStripStylesTransformer.js . I changed my jest.config.js as following, and it still doesn't work. The same error is produced.

// https://github.com/thymikee/jest-preset-angular#brief-explanation-of-config
module.exports = {
  preset: 'jest-preset-angular',
  roots: ['src'],
  coverageDirectory: 'reports',
  setupFilesAfterEnv: ['<rootDir>/src/setup-jest.ts'],
  moduleNameMapper: {
    '@app/(.*)': '<rootDir>/src/app/$1',
    '@env': '<rootDir>/src/environments/environment'
  },
  globals: {
    'ts-jest': {
      allowSyntheticDefaultImports: true,
      tsConfig: '<rootDir>/tsconfig.spec.json',
      astTransformers: [
        "jest-preset-angular/build/InlineFilesTransformer",
        "jest-preset-angular/build/StripStylesTransformer"
      ]
    }
  },
  // Do not ignore librairies such as ionic, ionic-native or bootstrap to transform them during unit testing.
  transformIgnorePatterns: ['node_modules/(?!(jest-test|@clr))']
};

EDIT 2

I tried both syntax proposed by Angular 8 and jest - File not found: jest-preset-angular/InlineHtmlStripStylesTransformer.js .

(https://stackoverflow.com/a/58499156/8902132) (https://stackoverflow.com/a/68728271/8902132)

module.exports = {
  preset: 'jest-preset-angular',
  roots: ['src'],
  coverageDirectory: 'reports',
  setupFilesAfterEnv: ['<rootDir>/src/setup-jest.ts'],
  moduleNameMapper: {
    '@app/(.*)': '<rootDir>/src/app/$1',
    '@env': '<rootDir>/src/environments/environment'
  },
  globals: {
    'ts-jest': {
      allowSyntheticDefaultImports: true,
      tsConfig: '<rootDir>/tsconfig.spec.json',
      astTransformers: {
        before:[
          "jest-preset-angular/build/InlineFilesTransformer",
          "jest-preset-angular/build/StripStylesTransformer"
        ]
      }
    }
  },
  // Do not ignore librairies such as ionic, ionic-native or bootstrap to transform them during unit testing.
  transformIgnorePatterns: ['node_modules/(?!(jest-test|@clr))']
};

In both cases the test command output:

 FAIL  src/app/modules/hypervision/hypervision.service.spec.ts
  ● Test suite failed to run

    File not found: jest-preset-angular/InlineHtmlStripStylesTransformer.js (resolved as: /path/to/project/client/jest-preset-angular/InlineHtmlStripStylesTransformer.js)

      at ConfigSet.resolvePath (node_modules/ts-jest/dist/config/config-set.js:725:19)
      at node_modules/ts-jest/dist/config/config-set.js:250:98
          at Array.map (<anonymous>)
      at ConfigSet.get (node_modules/ts-jest/dist/config/config-set.js:250:64)
      at ConfigSet.<anonymous> (node_modules/ts-jest/dist/util/memoize.js:44:24)
      at ConfigSet.get (node_modules/ts-jest/dist/config/config-set.js:315:41)
      at ConfigSet.<anonymous> (node_modules/ts-jest/dist/util/memoize.js:44:24)
      at ConfigSet.get (node_modules/ts-jest/dist/config/config-set.js:585:32)
      at ConfigSet.<anonymous> (node_modules/ts-jest/dist/util/memoize.js:44:24)
      at ConfigSet.get (node_modules/ts-jest/dist/config/config-set.js:603:25)

Edit 3

I've abandonned the idea of using jest for testing my project. I've completly removed jest and installed karma.

Before installing karma, I've tried to re-install completly jest in my project, but even then it didn't work. In my opinion, the main reason for jest to not work is the mismatch between the version of jest, jest-preset-angular, @angular-builders/jest.

0 Answers
Related