Perform tests based on component lifecycle

0

I need to run the tests following the lifecycle of the Angular. I could not identify any tool or way to do this. Basically it would call the tests based on lifecycle.

Here's a simple example:

my-component.ts :

import { Component } from '@angular/core';

@Component({
  selector: 'my-component', 
  template: '...'
})
export class MyComponent implements OnInit, AfterViewChecked {
  constructor(private element: ElementRef) {}

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

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

my-component.spec.ts

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { MyComponent } from './my.component';

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

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  // DEVERIA SER CHAMADO NO ON INIT
  it('should initiate', () => {
    expect(compiled.textContent).toEqual('Init');
  });

  // DEVERIA SER CHAMADO APÓS O LIFECYCLE AfterViewChecked
  it('should render view', () => {
    expect(compiled.textContent).toEqual('ViewChecked');
  });
});
    
asked by anonymous 08.08.2018 / 20:08

1 answer

0

You can call the component's own function:

 it('should initiate', () => {
    component.ngOnInit();
    expect(compiled.textContent).toEqual('Init');
  });
    
09.08.2018 / 09:26