如何使用* ng-if隐藏角度4中的元素?

时间:2018-05-28 05:58:30

标签: angular

我正在尝试在角度2中测试@Input@Input隐藏或显示我的p标记。我想使用jasmine测试此功能。

这是我的组件

import { Component,Input } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 4';
  @Input() enable:boolean
  constructor() { }
}

测试代码。

describe('@Input property ', () => {
    it('will not show p tag', () => {
      component.enable = false;
      fixture.detectChanges();
      PEl = fixture.debugElement.query(By.css('p'));
      console.log(PEl.nativeElement);
      expect(PEl.nativeElement.length).toEqual(0);
    })
  })

https://stackblitz.com/edit/angular-testing-wzxrin?file=app%2Fapp.component.spec.ts

2 个答案:

答案 0 :(得分:1)

测试它是否为空,而不是它是否有长度。

component.enable = false;
fixture.detectChanges();
PEl = fixture.debugElement.query(By.css('p'));
console.log(PEl.nativeElement);
expect(PEl).toBeUndefined();

答案 1 :(得分:0)

测试null不是长度

component.enable = false;
fixture.detectChanges();
PEl = fixture.debugElement.query(By.css('p'));
expect(PEl).tobeNull();