创建DOM组件列表的测试函数

Testing function that creates a list of DOM components

本文关键字:测试 函数 列表 DOM 组件 创建      更新时间:2023-09-26

我有一个创建组件数组的函数。每个组件都是一个带有几个内部div的外部div。

function createDivs(quizQuestions) {
    var returnElements = new Array();
    $.each(quizQuestions.questions, function(i, val){
    // create the div.
    quizDiv = $('<div class="questionContainer radius">')
    questionDiv = $('<div class="question"><b><span>QuestionText</span></b></div>');
    quizDiv.append(questionDiv);
    // Now change the question div text.
    questionDiv.text = val.question;
    answerDiv = $('<div class="answerswers">');
    // ...
    // ...
    // Now the answers.
    questionDiv.append(answerDiv);
    returnElements[i] = quizDiv;
});
return returnElements; 

我传递JSON,如:

   {questions:[{"question":"Name the best Rugby team?",
   "answerswers":["Leinster", "Munster", "Ulster", "Connaught"],
   "correct_answer":"Leinster"},
   {"question":"Name the best DJ?",
   "answerswers":["Warren K", "Pressure", "Digweed", "Sasha"],
   "correct_answer":"Leinster"}]};

我想写一个简单的单元测试,这样我就可以测试返回的div数组是否有意义

提示吗?

另外,是我更好地返回一个DOM组件或只是文本?后者更容易测试。

谢谢。

不确定你到底想测试什么,但尽可能多地在字符串中创建html以减少函数调用的性能要高得多。另外,append的开销很大,所以最终为JSON表示的所有新内容创建一个字符串将是最大的性能增益。

在我看来,它也使代码更具可读性,因为片段的顺序与html编辑器中的顺序相同

示例(我的首选是创建所有字符串片段的数组,连接也常用):

var newcontent = [];
$.each(quizQuestions.questions, function(i, val) {
    newcontent.push('<div class="questionContainer radius">');
    newcontent.push('<div class="question"><b><span>' + val.question + '< /span></b > < /div>');
    $.each(val.answers, function(idx, answer) {
        newcontent.push('<div class="answerswers">' + answer + '</div > ')
    })
    newcontent.push(' </div></div > ');
});

然后添加内容到DOM:

$('#someDiv').append( newcontent.join(''));

免责声明:未完全检查标签是否正确关闭/嵌套。