`

Angular UT中Component constructor和ngOnInit的调用顺序

阅读更多

写Angular UT总是犯低级错误,烦躁!

 

当第一个it跑完之后,第二个it跑之前,会执行component的清理操作。会调用component的ngOnDestroy方法!!!如果只有第一个it而不存在第二个it,那么就不会执行cleanup, 就不会调用ngOnDestroy方法!!!

const component;
beforeEach(() => {
    store = TestBed.get(Store);

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

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

  it('should xxx', () => {
    xxxx
  });

 

列一个加载顺序

// Footer component 
@Component({
  selector: 'app-footer',
  templateUrl: './footer.html',
  styleUrls: ['./footer.scss']
})
export class FooterComponent implements OnInit {

  @Input() data$: Observable<any>;

  constructor() {
    console.info(Date.now() + ' constructor run');
  }

  ngOnInit() {
    console.info(Date.now() + ' ngOnInit run');
  }
}

// Test case

@Component({
  selector: 'app-test',
  template: `
    <div class="test">
      <app-footer [data$]="data$"></app-footer>
    </div>`
})
export class TestComponent {
  data$ = of(mockData);
  @ViewChild(FooterComponent)
  footer: FooterComponent;
}
describe('FooterComponent', () => {
  let component: TestComponent;
  let fixture: ComponentFixture<TestComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [FooterComponent, TestComponent],
      schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA]
    })
      .compileComponents();
  }));

  beforeEach(() => {

  });


  it('should run', async(() => {

    // 1542164082785 constructor run
    // fixture = TestBed.createComponent(TestComponent);

    // 1542164188797 constructor run
    // fixture = TestBed.createComponent(TestComponent);
    // component = fixture.componentInstance;

    // 1542164494371 constructor run
    // 1542164494456 ngOnInit run
    // fixture = TestBed.createComponent(TestComponent);
    // component = fixture.componentInstance;
    // fixture.detectChanges();

    // 1542164608085 constructor run
    // const fixture2 = TestBed.createComponent(FooterComponent);

    // 1542165401505 constructor run
    // const fixture2 = TestBed.createComponent(FooterComponent);
    // const component2 = fixture2.componentInstance;

    // 1542165521337 constructor run
    // 1542165521376 ngOnInit run
    //const fixture2 = TestBed.createComponent(FooterComponent);
    //const component2 = fixture2.componentInstance;
    //component2.data$ = of(mockData);
    //fixture2.detectChanges();
	
    expect(true).toBe(true);
  }));
});

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics