Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JEST to run Angular component test gives cannot find module

Using Jest for the first time. Used the following code to initialze a component testing:

describe('CreateComponent', () => {
  let component: CreateQuoteComponent;
  let fixture: ComponentFixture<CreateQuoteComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
        declarations: [ CreateQuoteComponent ]
    });
    fixture = TestBed.createComponent(CreateQuoteComponent);
    component = fixture.componentInstance;
  }));

  test('should exist', () => {
    expect(component).toBeDefined();
  });
});

When running, for some of the imports in the component gives

Test suite failed to run Cannot find module' with ' 
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:259:17)
      at Object.<anonymous> (src/app/modules/xxx/components/landing/create/create.component.ts:19:1)

any leads for this or is there known workaround?

like image 456
Juliyanage Silva Avatar asked Jul 11 '26 10:07

Juliyanage Silva


2 Answers

I figured the issue out. Seems JEST cannot resolve relative paths that we configure inside the app like '@' signs so we need to provide the jest moduleNameMapper like below:

"jest": {
    "preset": "jest-preset-angular",
    "setupTestFrameworkScriptFile": "<rootDir>/src/jest.ts",
    "moduleNameMapper": {
      "@oshc(.*)": "<rootDir>/src/app/modules/oshc/$1",
      "@shared(.*)": "<rootDir>/src/app/@shared/$1"
    }

},

UPDATE : There will be another problem of JEST cannot find modules inside node_modules of your root folder. For this add the follwoing to jest configuration for module directories : "moduleDirectories": [ "node_modules", "src" ]

like image 158
Juliyanage Silva Avatar answered Jul 14 '26 07:07

Juliyanage Silva


In my case I changed the absolute path to the relative path and it worked. The change must be made in both component.ts and spec.ts files

For example, use this import:

import { GenericService } from '../../../shared/services/generic.service';

Instead of:

import { GenericService } from 'src/app/shared/services/generic.service';
like image 40
Julio Cesar Brito Gomes Avatar answered Jul 14 '26 05:07

Julio Cesar Brito Gomes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!