0

I've created custom directive to populate auto dash. Here is full custom directive code in stackblitz. May i know how to test following lines from mask.ts in jasmine (unit test)?

mask.ts

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

mask.spec.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;
  });
});
2
  • Have you tried this: stackoverflow.com/questions/47101648/… Commented Mar 9, 2020 at 15:22
  • @Ali yes. I tried few methods as well. None of them working for me. Commented Mar 9, 2020 at 15:55

1 Answer 1

2

Try:

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(""); 
  });
Sign up to request clarification or add additional context in comments.

2 Comments

input returning true now. How I can acheive let trimmed = input.value.replace(/\s+/g, '');
Check my edit, trimmed is a local variable so it will be difficult to test.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.