无法使用 Jest 在我的单元测试 js 文件中 inject/mock 文档?

Unable to inject/mock document in my unit test js file with Jest?

首先我是一个BE开发者。我们的项目中有一些 js 文件,我们想为其编写一些单元测试。 Jest 是我们选择的框架。我正在尝试为以下文件编写单元测试:

  "use strict";

  // when dialog gets injected
  $(document).on("foundation-contentloaded", function (e) {
      // if there is already an initial value make sure the according target element becomes visible
      $("[data-dialog-checkbox-showhide]", e.target).each(function () {
        showHide($(this));
      });
  });

  $(document).on("change", "[data-dialog-checkbox-showhide]", function () {
      showHide($(this));
  });

  function showHide(el) {

      // get the selector to find the target elements. its stored as data-.. attribute
      var target = el.data("dialogCheckboxShowhideTarget");

      // is checkbox checked?
      var checked = el.prop('checked');

      if (checked) {
          $(target).each(function () {
              // if checkbox is checked, we set the value to empty string.
              $(this).val('').attr('aria-required', false);
              // Hide input field as well as label.
              $(this).parent().hide();
          });
      } else {
          $(target).each(function () {
              $(this).attr('aria-required', true);
              // Show input field as well as label.
              $(this).parent().show();
          });
      }
  }

})(document, Granite.$);

我写了下面的测试来检查是否调用了 showhide 方法:



describe("checkboxshowhide method:", () => {
  test("should call showHide method", () => {

    const $ = require('jquery');
    // Set up our document body
      document.body.innerHTML =
        '<div>' +
        '  <span id="username" />' +
        '  <button id="button" />' +
        '</div>';
    expect(showHide()).toBeCalled();
  });
});

但是,我遇到了错误

[INFO] [nodejs] ReferenceError: document is not defined [INFO] [nodejs] > 51 | })(document, Granite.$);

此外,一些关于如何测试其他方法的指示将非常有帮助。

我错过了测试文件的后续内容。

/**
 * @jest-environment jsdom
 */

我以为这是 javadoc 之类的注释。