7

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?

0

2 Answers 2

18

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" ]

Sign up to request clarification or add additional context in comments.

Comments

7

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';

1 Comment

I confirm that worked also for me. But the question is why? However, I would like to use absolute paths

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.