【问题标题】:unit testing angular 2(ionic 2) custom directive单元测试 angular 2(ionic 2) 自定义指令
【发布时间】:2018-03-21 15:30:50
【问题描述】:

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

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

我尝试了很多方法来测试它,但我无法设置值。我可以通过导入FormsModule 并绑定输入来获得ngControl

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

这里是测试用例sn-p

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 这样的测试用例。如何测试?

【问题讨论】:

    标签: javascript angular unit-testing ionic2 testbed


    【解决方案1】:

    只需覆盖对象。

    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 引用了您的指令)

    【讨论】:

    • 我只是错过了对指令的引用。非常感谢!
    猜你喜欢
    • 2017-02-16
    • 1970-01-01
    • 2017-08-08
    • 2016-12-25
    • 1970-01-01
    • 2018-11-15
    • 2020-08-05
    • 2016-12-29
    相关资源
    最近更新 更多