DEV Community

vinay kumar
vinay kumar

Posted on

write testcases for the below functions in Angular TypeScript using Jasmin-karma.

open(): void {
this.isActivate = true;
document.body.appendChild(this.element);
this.element.style.display = 'block';
document.body.classList.add('tfb-modal-open', 'body--no-scroll');
setTimeout(() => {
const focusableElements =
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';
const modal = document.querySelector('#tfb-modal'); // select the modal by it's id
console.log("modal", modal);

  const firstFocusableElement = modal.querySelectorAll(focusableElements)[0] as HTMLInputElement;
  console.log("firstFocusableElement", firstFocusableElement);
  // get first element to be focused inside modal
  const focusableContent = modal.querySelectorAll(focusableElements);
  console.log("focusableContent", focusableContent);
  let lastFocusableElement: any;
  if (focusableContent.length <= 2) {
    lastFocusableElement = focusableContent[focusableContent.length - 2] as HTMLInputElement;
    console.log("lastFocusableElement_if", lastFocusableElement);
     // get last element to be focused inside modal
  } else {
    lastFocusableElement = focusableContent[focusableContent.length - 1] as HTMLInputElement;
    console.log("lastFocusableElement_else", lastFocusableElement);
     // get last element to be focused inside modal
  }

  document.addEventListener('keydown', (e) => {
    // tslint:disable-next-line: deprecation
    const isTabPressed = e.key === 'Tab' || e.keyCode === 9;
    if (!isTabPressed) {
      return;
    }
    if (e.shiftKey) { // if shift key pressed for shift + tab combination
      if (document.activeElement === firstFocusableElement) {
        lastFocusableElement.focus(); // add focus for the last focusable element
        e.preventDefault();
      }
    } else { // if tab key is pressed
      if (document.activeElement === lastFocusableElement) {
        // if focused has reached to last focusable element then focus first focusable
        // element after pressing tab
        firstFocusableElement.focus(); // add focus for the first focusable element
        e.preventDefault();
      }
    }
  });

  firstFocusableElement.focus();
}, (1000));
Enter fullscreen mode Exit fullscreen mode

}

Top comments (0)