0

I have a directive with restricts user from Inputting special characters. Trying to write a unit test that validates to make sure user is not able to input special characters.

Below I am trying to simulate keydown event when user enters A@ - and need to test only A was allowed to be entered. Looks like the input is not getting updated with these values via events. console.log(input.value) prints empty string. The only way I can set the value is input.value but in that case I am able to set special characters as well which is not what I want.

Anyway to reflect user input and validate to make sure special character was not allowed?

 it('should not allow special chars', () => { component.regexInput = '[a-zA-Z0-9\-\_ ]{1,25}'; fixture.detectChanges(); const input = fixture.nativeElement.querySelector('input'); const event = new KeyboardEvent("keydown", { "key": "A" }); input.dispatchEvent(event); fixture.detectChanges(); const event2 = new KeyboardEvent("keydown", { "key": "@" }); input.dispatchEvent(event2); fixture.detectChanges(); console.log(input.value); expect(input.value).toEqual('A'); }); 

    1 Answer 1

    0

    It seems you still have the old input selected.

    Try:

    it('should not allow special chars', async () => { component.regexInput = '[a-zA-Z0-9\-\_ ]{1,25}'; fixture.detectChanges(); const input = fixture.nativeElement.querySelector('input'); const event = new KeyboardEvent("keydown", { "key": "A" }); input.dispatchEvent(event); fixture.detectChanges(); const event2 = new KeyboardEvent("keydown", { "key": "@" }); input.dispatchEvent(event2); fixture.detectChanges(); await fixture.whenStable(); const newInput = fixture.nativeElement.querySelector('input'); // grab a new reference here console.log(newInput.value); expect(newInput.value).toEqual('A'); }); 

    The async and await fixture.whenStable() can be optional. First try to do it without those and see if it works. If it doesn't, add async and fixture.whenStable() because I remember some aspects of Angular forms are asynchronous.

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.