简体   繁体   English

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

[英]unit testing angular 2(ionic 2) custom directive

I made a custom directive for text masking in my ionic application. 我在离子应用程序中为文本屏蔽设置了自定义指令。 The directive is for input text masking for the phone number. 该伪指令用于电话号码的输入文本屏蔽。 It uses ngControl to get and set the values of the input field. 它使用ngControl来获取和设置输入字段的值。

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

I tried many approaches to test it but I was unable to set the value. 我尝试了多种方法对其进行测试,但无法设置该值。 I was able to get ngControl by importing the FormsModule and binding the input. 我能够通过导入FormsModule并绑定输入来获取ngControl

But I still can't get value as this.ngControl.control.value . 但是我仍然不能像this.ngControl.control.value那样获得价值。 When I type in the input field, it works fine but unable to define test case. 当我在输入字段中键入内容时,它可以正常工作,但无法定义测试用例。

here is the test case snippet 这是测试用例片段

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)');
  });
}

This is my test component : 这是我的测试组件:

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

I want to write a test case like this expect(element.value).toEqual('(999)-999-9999 . How can I test it? 我想编写一个这样的测试用例expect(element.value).toEqual('(999)-999-9999 。如何测试它?

Simply overwrite the object. 只需覆盖对象。

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)');
}

(I assume you have a reference to your directive through the variable directive ) (我假设您通过变量directive引用了您的directive

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM