业力/茉莉花:无法使用detectChanges()检测到@Input属性的更改

时间:2018-07-23 14:50:33

标签: angular unit-testing karma-jasmine

我试图更改组件的@Input属性,并基于new属性,尝试检查按钮是否已启用。引用代码here

我正在遵循此链接中描述的确切步骤,但不起作用。我正在使用detectChanges()更改值,但未达到预期的结果。

HTML:

<form>
    <label>Email</label>
    <input type="email"
           #email>
    <label>Password</label>
    <input type="password"
           #password>
    <button type="button" 
            (click)="login(email.value, password.value)"
            [disabled]="!enabled">Login
    </button>
  </form>

组件:

@Input() enabled = true;

规格:

describe('testing app component', () => {
  let component;
  let service;
  let fixture;
  let element;
  let atag;
  let loginEl;
  let passwordEl;
  let submitEl;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
      providers: [
        AppService
      ]
    }).compileComponents();

    // create component fixture
    fixture = TestBed.createComponent(AppComponent);

    // get component's instance for testing
    component = fixture.debugElement.componentInstance;

    // getting service instance from tets bed
    service = TestBed.get(AppService);

    // getting button element
    fixture.detectChanges();
    element = fixture.debugElement.query(By.css('button'));
    atag = fixture.debugElement.query(By.css('a'));

    submitEl = fixture.debugElement.query(By.css('button'));
    loginEl = fixture.debugElement.query(By.css('input[type=email]'));
    passwordEl = fixture.debugElement.query(By.css('input[type=password]'));
  });

  it('testing input property: @Input enabled', () => {
    expect(component.enabled).toBe(true);
    expect(submitEl.nativeElement.disabled).toBeFalsy();
    component.enabled = false;
    fixture.detectChanges();
    expect(submitEl.nativeElement.disabled).toBeTruthy();
  });
});

但是此规范引发错误:Error: Expected false to be truthy.

1 个答案:

答案 0 :(得分:1)

编辑

您创建组件的方式也不正确。必须是

component = fixture.componentInstance;

DEMO

原始

在视图更新后(即,在调用dom之后),应再次获取detectChanges()元素。如果不这样做,那么将根据更新之前存在的视图对测试进行验证。

submitEl = fixture.debugElement.query(By.css('button'));

-测试规范

it('testing input property: @Input enabled', () => {
    expect(component.enabled).toBe(true);
    expect(submitEl.nativeElement.disabled).toBeFalsy();
    component.enabled = false;
    fixture.detectChanges();

     // fetch dom element again
    submitEl = fixture.debugElement.query(By.css('button'));
    expect(submitEl.nativeElement.disabled).toBeTruthy();
});