【问题标题】:How to make tests based on angular component lifecycle如何根据角度组件生命周期进行测试
【发布时间】:2018-08-08 19:12:31
【问题描述】:

我需要按照 Angular 组件 lifecycle 进行测试。我找不到制作这个的方法或工具。基本上想在给定的生命周期后调用测试。

以下示例:

my-component.ts

@Component(...)
export class MyComponent implements OnInit, AfterViewChecked {
  constructor(private element: ElementRef) {}

  ngOnInit() {
    this.element.innerHTML = 'Init';
  }

  ngAfterViewChecked() {
    this.element.innerHTML = 'AfterViewChecked';
  }
}

my-component.spec.ts

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [MyComponent]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement;
  });

  // SHOULD BE CALLED AFTER ON INIT
  it('should initiate', () => {
    expect(compiled.textContent).toEqual('Init');
  });

  // SHOULD BE CALLED AFTER THE LIFECYCLE AfterViewChecked
  it('should render view', () => {
    expect(compiled.textContent).toEqual('ViewChecked');
  });
});

【问题讨论】:

    标签: javascript angular unit-testing testing


    【解决方案1】:

    对于 ngOnInit 你可以这样调用它,对于其他生命周期钩子也是如此

    component.ngOnInit();
    

    例子

    it('inner test should be Init', () => {
     expect(inner text).toEqual('Init'); // false
     component.ngOnInit();
     fixture.detectChanges();
     expect(inner text).toEqual('Init'); // pass
    });
    

    【讨论】:

    • 但是这样做如何确保视图已经被检查?
    • 你可以运行 fixture.detectChanges();就在 ngOnInit 调用之后
    猜你喜欢
    • 2023-03-09
    • 1970-01-01
    • 2019-11-27
    • 2020-03-20
    • 2019-08-13
    • 2014-01-29
    • 2017-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多