首页 文章

角度单位测试输入值

提问于
浏览
21

我一直在阅读用于单元测试的官方Angular2文档(https://angular.io/docs/ts/latest/guide/testing.html),但我正在努力设置组件的输入字段值,以便它反映在组件属性中(通过ngModel绑定) . 屏幕在浏览器中工作正常,但在单元测试中我似乎无法设置字段值 .

我正在使用下面的代码 . “夹具”已正确初始化,因为其他测试工作正常 . “comp”是我的组件的实例,输入字段通过ngModel绑定到“user.username” .

it('should update model...', async(() => {
    let field: HTMLInputElement = fixture.debugElement.query(By.css('#user')).nativeElement;
    field.value = 'someValue'
    field.dispatchEvent(new Event('input'));
    fixture.detectChanges();

    expect(field.textContent).toBe('someValue');
    expect(comp.user.username).toBe('someValue');
  }));

我的Angular2版本: "@angular/core": "2.0.0"

3 回答

  • 4

    输入没有textContent,只有一个值 . 所以 expect(field.textContent).toBe('someValue'); 没用 . 那个_1391534失败了 . 第二个期望应该通过 . 这是一个完整的测试 .

    @Component({
      template: `<input type="text" [(ngModel)]="user.username"/>`
    })
    class TestComponent {
      user = { username: 'peeskillet' };
    }
    
    describe('component: TestComponent', () => {
      beforeEach(() => {
        TestBed.configureTestingModule({
          imports: [FormsModule],
          declarations: [ TestComponent ]
        });
      });
    
      it('should be ok', async(() => {
        let fixture = TestBed.createComponent(TestComponent);
        fixture.detectChanges();
        fixture.whenStable().then(() => {
          let input = fixture.debugElement.query(By.css('input'));
          let el = input.nativeElement;
    
          expect(el.value).toBe('peeskillet');
    
          el.value = 'someValue';
          el.dispatchEvent(new Event('input'));
    
          expect(fixture.componentInstance.user.username).toBe('someValue');
        });
      }));
    });
    
  • 40

    只需添加

    fixture.detectChanges();
    
    fixture.whenStable().then(() => {
      // here your expectation
    })
    
  • 0

    whenStable.then 函数中使用expect / assert,如下所示:

    component.label = 'blah';
        fixture.detectChanges();
    
        fixture.whenStable().then(() => {
                 expect(component.label).toBe('blah');
            }
    

相关问题