summaryrefslogtreecommitdiffstats
path: root/vid-webpack-master/src/app/shared/directives/inputPrevention/inputPreventionPattern.directive.spec.ts
blob: 846ff70f2852e3824b94874d0a06796eb8d3f01a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import {TestBed, ComponentFixture} from '@angular/core/testing';
import {Component, DebugElement} from "@angular/core";
import {By} from "@angular/platform-browser";
import { InputPreventionPatternDirective } from './inputPreventionPattern.directive';

@Component({
  template: `<input 
    patternInput
    pattern="^[a-zA-Z0-9_]*$">`
})
class TestHoverFocusComponent {
}


describe('InputPrevention Pattern Directive', () => {

  let component: TestHoverFocusComponent;
  let fixture: ComponentFixture<TestHoverFocusComponent>;
  let directiveInstance : InputPreventionPatternDirective;
  let inputEl: DebugElement;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [TestHoverFocusComponent, InputPreventionPatternDirective]
    });
    fixture = TestBed.createComponent(TestHoverFocusComponent);
    component = fixture.componentInstance;
    inputEl = fixture.debugElement.query(By.css('input'));
    directiveInstance = inputEl.injector.get(InputPreventionPatternDirective);
  });

  it('directive should be defined', () => {
    expect(directiveInstance).toBeDefined();
  });

  it('pattern exists', () => {
    expect(inputEl.nativeElement.pattern).toEqual('^[a-zA-Z0-9_]*$');
  });

  it('kepress legal input', () => {
    fixture.detectChanges();
    inputEl.nativeElement.value = "legalInput";
    expect(new RegExp(inputEl.nativeElement.pattern).test(inputEl.nativeElement.value)).toBeTruthy();
  });

  it('kepress illegal input', () => {
    inputEl.triggerEventHandler('kepress', " ");
    fixture.detectChanges();
    expect(inputEl.nativeElement.value).toBe('');
  });

  it('kepress event legal input should return event', () => {
    const event = <any>{ key: 'A' };
    inputEl.nativeElement.value = "legalInput";
    let result = directiveInstance.onKeypress(event);
    expect(result).toBe(event);
  });

  it('kepress event illegal input should prevent default', () => {
    const event = <any>{key: '-', preventDefault : function () {} };
    spyOn(event, 'preventDefault');
    inputEl.nativeElement.value = "-";
    let result = directiveInstance.onKeypress(event);
    expect(event.preventDefault).toHaveBeenCalled();
  });
});