【发布时间】: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