【问题标题】:Angular Circular Dependency issue in Jest unit testsJest 单元测试中的 Angular 循环依赖问题
【发布时间】:2018-06-03 05:37:05
【问题描述】:

我有以下 Angular 组件。它们在我的应用程序中编译并运行良好。但是,当我在 Jest 测试中包含该模块时,会出现错误。我不知道这是否是 typescript 配置、Angular、Jest 或组合的问题。

组件:

@Component({
  selector: 'child-component',
  template: '<div>Child here.</div>'
})
export class ChildComponent {
  constructor( @Inject(forwardRef(() => ParentComponent)) private 
parentComponent: ParentComponent ) { }
}

@Component({
  selector: 'parent-component',
  template: '<div>
    <child-component></child-component>
    <child-component></child-component>
  </div>'
})
export class ParentComponent{
  @ViewChildren(ChildComponent) _children: QueryList<ChildComponent>;
}

const EXPORTED_DECLARATIONS = [
  ChildComponent,
  ParentComponent
];

@NgModule({
  exports: [EXPORTED_DECLARATIONS],
  declarations: [EXPORTED_DECLARATIONS]
})
export class TestingModule { }

如您所见,存在循环依赖。但是,它应该用@Inject(forwardRef(() =&gt; ParentComponent)) 修复,但这不起作用。

规格:

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TestingModule } from './test';
import { Component, forwardRef } from '@angular/core';

describe( 'TestComponent', () => {

  let component: TestTestComponent;
  let fixture: ComponentFixture<TestComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [ TestComponent ],
      imports: [
        TestingModule
      ]
    });

    fixture = TestBed.createComponent(TestComponent);
    component = fixture.componentInstance;
  } );

  it( 'default', () => {
    expect( fixture ).toMatchSnapshot();
  });

});

@Component({
  selector: 'test-test-1234',
  template: `<parent-component></parent-component>`
})
class TestComponent { }

我在运行单元测试时收到以下错误。

ReferenceError: ParentComponent is not defined

我想补充一点,如果我对 Jasmine / Karma 执行相同操作,我不会收到此错误。

【问题讨论】:

    标签: angular typescript jestjs


    【解决方案1】:

    当我将这两个组件分成单独的文件时,问题就解决了。

    【讨论】:

      【解决方案2】:

      尝试在你的测试中使用

       const el = fixture.debugElement.nativeElement;
       expect(el.outerHTML).toMatchSnapshot();
      

      如果您将升级到最新版本的 angular(现在是 5.2.9),这些测试将耗尽内存!

      【讨论】:

      • 您好,我刚刚看到您对我的问题的回复。你提出了一个有趣的观点。我最近遇到了内存问题,并且测试需要很长时间才能运行。这可能是根本问题。但是,我已经进行了您建议的更改,但这会更改快照,因此它们的格式不正确。你有使用过这个和 jest-preset-angular 库的经验吗?谢谢你的帖子。
      猜你喜欢
      • 2023-04-05
      • 2021-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多