简体   繁体   中英

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

First of all I am a BE developer. We have a few js files in our project for which we want to write some unit tests. Jest is the framework we choose. I am trying to write unit tests for following file:

  "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.$);

I have written following test just to check if the method showhide is called:



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();
  });
});

However, I am getting error

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

Also, some pointers to how I can test other methods would be really helpful.

I had missed following on top of the test file.

/**
 * @jest-environment jsdom
 */

I thought this was comment like javadoc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM