如何在没有输入的情况下测试 JS 函数(使用 Jest)

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

我制作了一个包含侧边栏的简单网站。单击边栏图标,它应该打开或关闭。我编写的以下代码正是这样做的。


/** 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;
  }
};

现在我必须用 Jest 为这个功能编写一个测试,但我不知道从哪里开始。我无法为它提供任何输入并比较预期的输出。有没有人对新手有一些提示?

谢谢!

如果您的函数没有显式输出,并不意味着它什么都不做。该函数有一些“行为”,在您的情况下,它会进行一些 DOM 操作。所以你应该测试一下。

您有两种选择:

  1. 模拟需要 DOM API 功能,并期望模拟对象的道具具有您喜欢的形状。
  2. 使用其他工具通过快照测试呈现实际 HTML。