【问题标题】:Unable to inject/mock document in my unit test js file with Jest?无法使用 Jest 在我的单元测试 js 文件中注入/模拟文档?
【发布时间】:2021-10-28 15:39:00
【问题描述】:

首先,我是一名 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: 文档未定义 [INFO] [节点] > 51 | })(文档,Granite.$);

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

【问题讨论】:

    标签: javascript unit-testing jestjs


    【解决方案1】:

    我错过了对测试文件的关注。

    /**
     * @jest-environment jsdom
     */
    

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

    【讨论】:

      猜你喜欢
      • 2018-03-20
      • 2016-02-11
      • 2019-10-01
      • 2020-09-03
      • 1970-01-01
      • 2018-08-07
      • 2019-05-30
      • 2020-11-22
      • 1970-01-01
      相关资源
      最近更新 更多