代码之家  ›  专栏  ›  技术社区  ›  Whisher

角度单位测试道具从来都不是未定义的

  •  1
  • Whisher  · 技术社区  · 7 年前

    我不明白到底为什么

    BannerComponent should not have welcome message after construction
    Expected 'welcome' to be undefined.
    

    @Component({
      selector: 'iwdf-banner',
      template: `
        <p>
          {{me}}
        </p>
      `,
      styles: []
    })
    export class BannerComponent implements OnInit {
      me: string;
      constructor() { }
      ngOnInit() {
        this.me = 'welcome';
      }
    }
    

    //试验

    describe('BannerComponent', () => {
      let component: BannerComponent;
      let fixture: ComponentFixture<BannerComponent>;
    
      beforeEach(async(() => {
        TestBed.configureTestingModule({
          declarations: [ BannerComponent ]
        })
        .compileComponents();
      }));
    
      beforeEach(() => {
        fixture = TestBed.createComponent(BannerComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
      });
    
      it('should create', () => {
        expect(component).toBeTruthy();
      });
    
      it('should not have welcome message after construction', () => {
        expect(component.me).toBeUndefined();
      });
    
      it('should welcome logged in user after Angular calls ngOnInit', () => {
          component.ngOnInit();
          expect(component.me).toContain('welcome');
      });
    });
    
    2 回复  |  直到 7 年前
        1
  •  0
  •   Kevin Doyon Zephaniah Grunschlag    7 年前

    使命感 TestBed.createComponent 将调用组件的构造函数,但不会调用任何生命周期挂钩。

    这个 OnInit 生命周期挂钩将在您第一次调用时调用 fixture.detectChanges() me 有价值 welcome 而不是没有定义。

    您可以通过删除 fixture.detectChanges() beforeEach ,并将其移动到需要它的单个测试(除了一个失败的测试之外,其他所有测试都将如此)。你不需要打电话 ngOnInit fixture.detectChanges() .

    使命感 如果您想在没有角度测试台的情况下测试组件,那么手动测试可能会很有用——然后您必须自己处理依赖关系和生命周期,我不建议这样做。

        2
  •  1
  •   pascalpuetz    7 年前

    好的,TestBed确实运行了所有必要的生命周期钩子来检测更改。因此,可以预期变量已定义。不要使用 fixture.detectChanges()