【问题标题】:Using JEST to run Angular component test gives cannot find module使用 JEST 运行 Angular 组件测试会导致找不到模块
【发布时间】:2020-04-30 05:46:31
【问题描述】:

第一次使用 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();
  });
});

运行时,对于组件中的一些imports给出了

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)

这方面的任何线索或是否有已知的解决方法?

【问题讨论】:

    标签: angular testing jestjs


    【解决方案1】:

    我解决了这个问题。似乎 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 配置中: “模块目录”:[ “节点模块”, “源代码” ]

    【讨论】:

      猜你喜欢
      • 2022-06-12
      • 2018-11-09
      • 2019-10-30
      • 2022-08-23
      • 1970-01-01
      • 2022-08-23
      • 2022-11-09
      • 2020-04-25
      • 1970-01-01
      相关资源
      最近更新 更多