使用JEST运行Angular组件测试时出现找不到模块的错误

3

首次使用 Jest。通过以下代码来初始化组件测试:

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();
  });
});

运行时,某些组件中的导入存在问题

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)

这方面有何线索,或是否已知有解决方法?
2个回答

14

我已经解决了这个问题。看起来JEST无法解析我们在应用程序中配置的相对路径,例如 '@' 符号,因此我们需要提供类似下面的jest moduleNameMapper:

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

},

更新:还将出现JEST找不到根目录中node_modules内的模块的另一个问题。为此,请在jest配置中添加以下内容以进行模块目录设置: "moduleDirectories":[ "node_modules", "src" ]


4
在我的情况下,我将绝对路径改为相对路径,然后它就起作用了。更改必须在component.ts和spec.ts文件中进行。
例如,使用以下导入方式:
import { GenericService } from '../../../shared/services/generic.service';

改为:

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

我确认这对我也起作用了。但问题是为什么?然而,我想使用绝对路径。 - Andrew

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接