mercredi 8 août 2018

How to make tests based on angular component lifecycle

I need to make tests following the Angular component lifecycle. I could not find a way or tool to make this. Basically wanted to call the test after given lifecycle.

Following examples:

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

Aucun commentaire:

Enregistrer un commentaire