• [Angular & Unit Testing] Automatic change detection


    When you testing Component rendering, you often needs to call:

    fixture.detectChanges();

    For example:

    it('should display original title', () => {
      fixture.detectChanges();
      expect(el.textContent).toContain(comp.title);
    });
    
    it('should display a different test title', () => {
      comp.title = 'Test Title';
      fixture.detectChanges(); // After change the prop of comp instance, call detectChanges()
      expect(el.textContent).toContain('Test Title');
    });

    You can also set auto change detection:

    import { ComponentFixtureAutoDetect } from '@angular/core/testing';

    Add to providers:

    TestBed.configureTestingModule({
      declarations: [ BannerComponent ],
      providers: [
        { provide: ComponentFixtureAutoDetect, useValue: true }
      ]
    })

    Tests wit auto change detection:

    it('should display original title', () => {
      // Hooray! No `fixture.detectChanges()` needed
      expect(el.textContent).toContain(comp.title);
    });
    
    it('should still see original title after comp.title change', () => {
      const oldTitle = comp.title;
      comp.title = 'Test Title';
      // Displayed title is old because Angular didn't hear the change :(
      expect(el.textContent).toContain(oldTitle);
    });
    
    it('should display updated title after detectChanges', () => {
      comp.title = 'Test Title';
      fixture.detectChanges(); // detect changes explicitly
      expect(el.textContent).toContain(comp.title);
    });
  • 相关阅读:
    设计模式之单例模式
    设计模式之原型模式
    设计模式之建造者模式
    设计模式之抽象方法模式
    设计模式之简单工厂模式
    java中内存分配
    java引用类型
    Oracle
    Oracle
    Oracle
  • 原文地址:https://www.cnblogs.com/Answer1215/p/7646550.html
Copyright © 2020-2023  润新知