gpt4 book ai didi

javascript - 如何使用 Mocha 测试私有(private)功能?

转载 作者:行者123 更新时间:2023-11-30 14:38:13 25 4
gpt4 key购买 nike

因为我是单元测试的新手,我想测试我的 javascript 代码,它非常困惑..我真的需要一些帮助谁可以告诉我问题的解决方案。??

if (!Notification) {
Notification = {};
else {
if (typeof Notification != "object") {
throw new Error(" already exists ");
}
}
Notification.admin = function() {
var res = {};
var prevent = "";

var DefaultValue = function(ans, type, commnon, status) {
var notify = type.concat(common);
if ($("#method").val() == "false" && type == "Text") {
if (status) {
return data = '<label class="checkbox-label"><input data-role="ux-checkbox" type="checkbox" disabled="disabled" data-type="' + notify + '" class="grid-checkbox">&nbsp;&nbsp</label>';
} else {
return data = '<label class="checkbox-label">' + '<span class="no-checkbox-label" >' + "-" + '</span>' + '</label>';
}
} else if (status) {
if (ans) {
return data = '<label class="checkbox-label"><input data-role="ux-checkbox" checked=checked type="checkbox" data-type="' + notify + '" class="grid-checkbox ">&nbsp;&nbsp</label>';
} else {
return data = '<label class="checkbox-label"><input data-role="ux-checkbox" type="checkbox" data-type="' + notify + '" class="grid-checkbox">&nbsp;&nbsp</label>';
}
} else {
return data = '<label class="checkbox-label">' + '<span class="no-checkbox-label" >' + "-" + '</span>' + '</label>';
}
};
this.init = function() {


};}; Notification.Obj = new Notification.admin();

$(document).ready(function() {

Notification.Obj.init();

});

这是我的私有(private)函数,我想对其进行单元测试,因为我正在使用 mocha 和 chai ..

我无法对这个函数进行单元测试

最佳答案

您不会为私有(private)方法编写测试。

公共(public)方法是类的公共(public)接口(interface)。那些从外面叫来的。私有(private)方法是您不关心的实现细节。

单元测试的范围是测试一个类的所有公共(public)方法。 (不,在类中公开私有(private)方法并不是解决这个问题的方法。)

将私有(private)方法的实际业务部分重构为新服务。该服务将具有通过公共(public)方法提供的功能。您可以测试该服务。在您当前的服务中,您可以注入(inject)该服务并使用其功能。

话虽这么说:您只能对没有副作用的方法进行单元测试,并且您可以模拟其依赖项(依赖项注入(inject))。

关于javascript - 如何使用 Mocha 测试私有(private)功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50095556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com