【问题标题】:Angular 4 (karma) Test input value to input filedAngular 4(业力)测试输入字段的输入值
【发布时间】:2019-02-18 21:09:07
【问题描述】:

我正在尝试测试通过键盘输入哪个值的事件。我的问题是在为输入字段设置值之后,当我打印它时,当我在 whenStable() 中打印它时,它打印为空。我想知道为什么这个值会在 Whitstable() 函数中被重置。我该如何解决?

我已推荐:Updating input html field from within an Angular 2 test 编写此测试用例。

it('Test input field value. ', async () => {
    const divDescription = fixture.debugElement.query(By.css('#costDescription'));

    divDescription.nativeElement.value = 'text';
    divDescription.nativeElement.dispatchEvent(new Event('input'));
    fixture.detectChanges();
    console.log('sendInput : ', divDescription.nativeElement.value); // prints 'text'
    fixture.whenStable().then(() => {
      console.log('sendInput : ', divDescription.nativeElement.value); // prints ''
      expect(divDescription.nativeElement.value).toContain('text');
    });
  });

【问题讨论】:

    标签: javascript angular unit-testing karma-jasmine


    【解决方案1】:

    删除 WhenStable() 使这种情况发生。

      it('Test input field value. ', async () => {
          const divDescription = fixture.debugElement.query(By.css('#costDescription'));
          divDescription.nativeElement.value = 'text';
          divDescription.nativeElement.dispatchEvent(new Event('input'));
          fixture.detectChanges();
          expect(divDescription.nativeElement.value).toContain('text');
      });
    

    【讨论】:

    • 上面的代码如图所示工作,但是我应该在托管 Angular 7 应用程序的 Jasmine 运行器中看到此内容。字段值在浏览器中没有变化?
    • 恕我直言,这个测试实际上毫无意义,因为你所做的只是测试你刚刚设置的东西的值。更好的测试是确保输入字段的更改也反映在您的模型中。
    【解决方案2】:

    您必须在 wheStable 中移动更改检测调用

    it('Test input field value. ', async () => {
     const divDescription = fixture.debugElement.query(By.css('#costDescription'));
    
     divDescription.nativeElement.value = 'text';
     divDescription.nativeElement.dispatchEvent(new Event('input'));
    
     console.log('sendInput : ', divDescription.nativeElement.value); // prints 'text'
     fixture.whenStable().then(() => {
      fixture.detectChanges(); // moved inside
      console.log('sendInput : ', divDescription.nativeElement.value); 
      expect(divDescription.nativeElement.value).toContain('text');
     });
    });
    

    【讨论】:

    • moving fixture.detectChanges() 不起作用,但是当我删除 fixture.whenStable(); 时测试用例通过了谢谢你的回复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-20
    • 2017-01-27
    • 2018-05-11
    • 2019-09-08
    • 2019-04-16
    • 2016-07-04
    相关资源
    最近更新 更多