Search code examples
ts-jestangular-libraryangular-jest

Running Jest tests in an angular library on Nx Monorepo


I've an nx monorepo project that have the following structure

apps/
libs/
 - angular/
  |- projects/
    |- angular-components/
      |- src/
        |- lib/
          |- componentA/
        |- tests/  
    package.kson
    tsconfig.lib.json
    tsconfig.spec.json 
  angular.json
  package.json
  jest.config.ts
  setup-jest.ts
  tsconfig.json
  tsconfig.spec.json 
 - react
..
jest.config.ts
package.json

I'm really struggeling to configure jest for the angular library ! I!ve followed the steps mentioned in ths article, it works for me with others projects, but not for this one !

I got the following error when running the test in InteliJ IDEA

Error: Jest: Failed to parse the TypeScript config file /Users/user/Desktop/my-nx-project/libs/angular/jest.config.ts
  TSError: ⨯ Unable to compile TypeScript:
jest.config.ts(6,27): error TS2306: File '/Users/user/Desktop/my-nx-project/libs/angular/node_modules/@types/jest/index.d.ts' is not a module.


here my libs/angular/jest.config.ts file

import type { Config } from 'jest';

const config: Config = {
  clearMocks: true,
  collectCoverage: true,
  coverageDirectory: "coverage",
  coverageProvider: "v8",
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  preset: 'jest-preset-angular',
  setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'],
  testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$',
  transform: {
    '^.+\\.(js|jsx|ts|tsx)$': 'ts-jest',
  },
  verbose: true,
};

export default config;

Any suggestions would be greatly appreciated.


Solution

  • for those encountering the same error in a monorepo project, the issue lies on dependency management, when we do an npm i in our specific lib, the dependencies are installed in the root project ! that's why

    To address this, a straight forward solution is to update the jest config as the following

    
    # libs/angular/jest.config.ts
    
    
    export default {
      clearMocks: true,
      collectCoverage: true,
      moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
      preset: 'jest-preset-angular',
    
      setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'],
      testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$',
    
      // should remove this ! or use `jest-preset-angular`instead of `ts-jest`
      // transform: {
      //   '^.+\\.(js|jsx|ts|tsx)$': 'ts-jest',
      // },
    
      verbose: true,
    }