How to write test case for if else statement in Angular (Jasmine)

Viewed 6988

I'm writing the test cases for custom directive in angular. Here is my code in stackblitz. Can anyone let me know how I can covered highlighted if else statement.

if (trimmedValue.length > 14) {
  // how to cover this statement
  trimmedValue = trimmedValue.substr(0, 14);
}

if (trimmedValue.substr(6, 2) !== '') {
  // how to cover this statement
  nricNumber.push(trimmedValue.substr(6, 2));
}

1 Answers

First you want to change the hostlistener in your directive to be like this or something similar depending on what the event you want to listen for is:

@HostListener('keydown', ['$event'])

Since you are putting the directive on an input you don't need to look for input in your directive, this will also make it only watch for 'keydown' on the host element. The first parameter of HostListener is supposed to be the event that you are listening for not just the name of the element.

So now if you change your test to emit a keydown event with the value in the input having a length greater than 14 you should hit that first if statement like the following:

it('should input value length > 14', () => {
    fixture = TestBed.createComponent(TestAutoDashNricComponent);
    const input = fixture.debugElement.query(By.directive(AutoDashNricDirective));

    // set value of input to something longer than 14
    input.nativeElement.value = '85060135229900000000123';

    const event = ({
      // set target to the input so you don't need to get it from the directive itself
      target: input.nativeElement, 
    } as unknown) as KeyboardEvent;

    // trigger keydown with created event
    input.triggerEventHandler('keydown', event);

    // check length of input value
    expect(input.nativeElement.value.length).toBe(14);
});

Also note that I set the target to point to the input that is calling the directive. That way you don't need to look for 'input' inside of the directive itself.

With this example you should be able to hit the other if else statements by doing something similar.

Related