0

I am transiting my testing from Karma to Jest in an Angular project, which has multiple pages. I can make the jest work for a simple component, which does not require many imports. However, for a large page, I have to manually re-import all the components again in the *.spec.ts files. Take one minimal example of pages:

app/
  pages/
    page1/
      index.ts
      page1.module.ts
      page1.component.ts
      feature1/
        feature1.component.ts
        feature1.component.spec.ts

page1.module.ts is importing necessary modules for this entire page:

import { Page1Component } from './page1.component';
import { Module1 } from '@shared/shared_modules/module3'
...
import { Module10 } from '@shared/shared_modules/module10'

@NgModule({
  imports: [
    Module1,
    ...,
    Module10
  ],
  declarations: [page1, Page1Component],
})
export class Page1Module {}

and index.ts is used to export all the modules to the child feature components:

export * from './page1.component';
export * from './page1.module';

To make the feature1.component.spec.ts work, I have to re-import all modules and components again. That said I need to import model1 ... module10 manually. However, my project already created more than 40 features/components, I would prefer an easier way to set up globally so that the feature's *.spec.ts can know how to read parent modules.

Is there any way to achieve this? I really appreciate it! Thank you

I have a basic setup in jest.config.ts using jest-preset-angular following this tutorial:

# jest.config.ts
module.exports = {
  preset: 'jest-preset-angular',
  roots: ['<rootDir>/src/'],
  setupFilesAfterEnv: ['<rootDir>/src/setup-jest.ts'],
  moduleNameMapper: {
    '^src/(.*)$': '<rootDir>/src/$1',
    '^@app/(.*)$': '<rootDir>/src/app/$1',
    '^@shared/(.*)$': '<rootDir>/src/app/shared/$1',
    '^@angular/(.*)$': '<rootDir>/node_modules/@angular/$1',
  },
  transformIgnorePatterns: ['node_modules/(?!lodash-es/.*|.*\\.mjs)'],
  moduleFileExtensions: ['ts', 'html', 'js', 'json', 'mjs']
};
4

0 回答 0