Perform tests based on component Lifecycle

Asked

Viewed 42 times

0

I need to run the tests following the Lifecycle Angular. I couldn’t identify any tool or way to do this. Basically it would be calling tests based on Lifecycle.

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

1 answer

0

You can call your own Component function:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.