代码之家  ›  专栏  ›  技术社区  ›  J-man

当使用jasmine in angular使用*ngif指令时,如何对元素是否可见进行单元测试

  •  8
  • J-man  · 技术社区  · 7 年前

    我有一个Angular6应用程序,正在编写一些单元测试,试图确定元素是否可见,或者仅仅基于 *ngIf 指令。

    标记:

    <div class="header" *ngIf="show">
        <div>...</div>
    </div>
    

    规范文件:

    it('should hide contents if show is false', () => {
        const button = debugElement.query(By.css('button')).nativeElement;
        button.click();   // this will change show to false
        fixture.detectChanges();
        expect(debugElement.query(By.css('.header')).nativeElement.style.hidden).toBe(true);
    });
    

    我好像拿不到 hidden 属性。angular是否使用另一种方法使用 *ngif公司 指令?我需要从 nativeElement 是吗?

    谢谢!

    4 回复  |  直到 6 年前
        1
  •  19
  •   Amit Chigadani    6 年前

    如果元素是隐藏的,那么它就不会在dom中呈现。

    你可以查一下

    expect(fixture.debugElement.query(By.css('.header'))).toBeUndefined();
    

    编辑 : toBeNull() 在上述情况下效果更好

    expect(fixture.debugElement.query(By.css('.header'))).toBeNull();
    

    而且在获取button元素时也有语法错误。 nativeElement 不是函数。

    换成这样:

    const button = fixture.debugElement.query(By.css('button')).nativeElement;
    
        2
  •  5
  •   lealceldeiro VonC    7 年前

    测试组件是否显示或未使用 ngIf 我试图得到元素(在这种情况下,您使用,即, debugElement.query(By.css('.header')).nativeElement )如果它应该被证明,我希望它是真的,否则是假的。

    像这样的:

    it('should hide contents if show is false', () => {
        // should be rendered initially
        expect(debugElement.query(By.css('.header')).nativeElement).toBeTruthy();
        //trigger change
        const button = debugElement.query(By.css('button')).nativeElement;
        button.click();   // this will change show to false
        fixture.detectChanges();
        // should not be rendered
        expect(debugElement.query(By.css('.header')).nativeElement).toBeFalsy();
    });
    

    另外,请记住,有时您需要使用 ComponentFixture#whenStable 要检测夹具是否稳定,请执行以下操作:

      it('should hide contents if show is false', () => {
        const fixture = TestBed.createComponent(AppComponent);
        fixture.whenStable().then(() => {
          // same test code here
        });
      });
    

    看到这个 working test 为了一个 component 哪一个 resembles this scenario 是的。

    见[ GitHub repository ]

        3
  •  1
  •   Drag13    7 年前

    使用ngif时,angular会从标记中完全删除节点。所以你需要检查这个元素不存在。

    Documentation says:

    ngif对表达式求值,然后在表达式分别为truthy或falsy时在其位置呈现then或else模板。

    更准确地说,它只是没有被渲染

        4
  •  1
  •   Dharma Raju    6 年前

    编写测试用例 *ngIf 条件使用 toBeNull 条件。

    试试下面的代码,对我有用。

    expect(fixture.debugElement.query(By.css('.header'))).toBeNull();
    
    推荐文章