Home > database >  How can I test a JS function without input (with Jest)
How can I test a JS function without input (with Jest)

Time:10-13

I made a simple website who contains a sidebar. On click on the Sidebar Icon, it should open or close. The following code that I wrote does extactly that.


/** toggleStatus is a anonymous function and can be called with its name */

let navStatus = false;

let toggleStatus = function () {
  let getSidebar = document.querySelector(".sidebar");
  let getSidebarUl = document.querySelector(".sidebar ul");
  let getSidebarLinks = document.querySelectorAll(".sidebar a");

  if (navStatus === false) {
    // if Sidebar is closed
    closeMenu();
    getSidebarUl.style.visibility = "visible";
    getSidebar.style.width = "272px"; // change width of sidebar so the content can fit

    let arrayLength = getSidebarLinks.length;
    for (let i = 0; i < arrayLength; i  ) {
      // Smake every List item Visible
      getSidebarLinks[i].style.opacity = "1";
    }

    navStatus = true;
  } else {
    // if Sidebar is open
    getSidebarUl.style.visibility = "hidden";
    getSidebar.style.width = "50px"; // change width of sidebar to the base Design

    let arrayLength = getSidebarLinks.length;
    for (let i = 0; i < arrayLength; i  ) {
      // make every List item invisible
      getSidebarLinks[i].style.opacity = "0";
    }

    navStatus = false;
  }
};

Now I have to write a test with Jest for this function, but I have no idea where to begin with. I cant feed it with any Input and compare the expected Output. Does anyone have some hints for a newbie?

Thank you!

CodePudding user response:

If your functions don't have explicit output it doesn't mean it does nothing. The function has some "behavior" and in your case, it does some DOM manipulations. So you should test for it.

You have two options to approach it:

  1. Mock needed DOM API functions and expect mocked object's props in the shape you like.
  2. Use other tools to render actual HTML with snapshot testing.
  • Related