代码之家  ›  专栏  ›  技术社区  ›  Gaurav Chaudhary

单元测试angular 2(ionic 2)自定义指令

  •  0
  • Gaurav Chaudhary  · 技术社区  · 7 年前

    我在ionic应用程序中为文本屏蔽制定了一个自定义指令。该指令用于电话号码的输入文本屏蔽。 它使用 ngControl 获取并设置输入字段的值。

    @HostListener('keyup', ['$event'])
    onKeyUp($event: any) {
            var inputValue = this.ngControl.control.value;   
            this.ngControl.control.setValue(this.getMaskedValue(inputValue));
        }
    }
    

    我尝试了许多方法来测试它,但我无法设置值。我能够 ngControl公司 通过导入 FormsModule 并绑定输入。

    但我仍然无法获得价值 this.ngControl.control.value 。当我在输入字段中键入时,它工作正常,但无法定义测试用例。

    下面是测试用例片段

    it('should have masked value', () => {
      fixture.detectChanges();
      let element = inputEl.nativeElement;
      element.value = '999';
      inputEl.nativeElement.dispatchEvent(new Event('keyup', key));
      fixture.detectChanges();
      fixture.whenStable().then(() => {
        expect(element.value).toEqual('(999)');
      });
    }
    

    这是我的测试组件:

    @Component({
      template: `<input type="text" [(ngModel)]="val"   customDirective="(999)-999-9999">`
    })
    class TestCustomDirectiveComponent {
      constructor(public formBuilder: FormBuilder) {}
      val = '';
    }
    

    我想写一个这样的测试用例 expect(element.value).toEqual('(999)-999-9999 。如何测试它?

    1 回复  |  直到 7 年前
        1
  •  0
  •   user4676340 user4676340    7 年前

    只需覆盖对象即可。

    it('should have masked value', () => {
      fixture.detectChanges();
      let element = inputEl.nativeElement;
      Object.defineProperty(
        directive.ngControl.control,
        'value',
        { writable: true, value: 'your value' }
      );
      directive.onKeyUp(null);
      expect(element.value).toEqual('(999)');
    }
    

    (我假设您通过变量引用了您的指令 directive )

    推荐文章