Angular: Как проверить событие клавиатуры в модульном тестировании с жасмином - PullRequest
0 голосов
/ 09 марта 2020

Я создал пользовательскую директиву для заполнения auto da sh. Вот полный код пользовательской директивы в stackblitz . Могу ли я узнать, как проверить следующие строки из mask.ts в жасмине (юнит-тест)?

mask.ts

@HostListener('input', ['$event'])
  onKeyDown(event: KeyboardEvent) {
    const input = event.target as HTMLInputElement;
    let trimmed = input.value.replace(/\s+/g, '');

mask.spe c .ts

@Component({
  template: `
    <input type="text" dobMask />
  `,
})
class TestdobMaskComponent {}

describe('dobMask', () => {
  let component: TestdobMaskComponent;
  let fixture: ComponentFixture<TestdobMaskComponent>;
  let inputEl: DebugElement;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [TestdobMaskComponent],
    });

    fixture = TestBed.createComponent(TestdobMaskComponent);
    component = fixture.componentInstance;
    inputEl = fixture.debugElement.query(By.css('input'));
  });
  it('should auto populate dash when reach 6 characters', () => {
    const input = inputEl.nativeElement as HTMLInputElement;
  });
});

1 Ответ

1 голос
/ 09 марта 2020

Попробуйте:

it('should auto populate dash when reach 6 characters', () => {
    const input = inputEl.nativeElement as HTMLInputElement;
    input.dispatchEvent(new KeyboardEvent('keydown', { key: ' ' }));
    // put a console.log in onKeyDown to make sure it is triggered.
    fixture.detectChanges();
    // grab a new reference
    const newInputEl = fixture.debugElement.query(By.css('input')) as HTMLInputElement;
    // trimmed is a local variable to the function so I don't know how you're going to test it
   // expect the space got trimmed
    expect(newInputEl.nativeElement.value).toEqual(""); 
  });
...