我想测试我的功能,而html就是这样。
这是我的功能。关于如何测试这个函数的任何好主意,使用代码会更有帮助。
<div id="showImgContainer"><img src="test.j" id="showImg" /></div>
function showIMG(){
$('#showImg').remove();
$('#showImgContainer').append('<img src="anothertest.jpg" />');
return false;
}
答案 0 :(得分:1)
当您想要进行测试用例时,您必须指定的是输入和预期输出。使用茉莉花,它以下列方式表示
it("name of your test case", function() {
// Your call with the inputs //
var result = showIMG();
// The expected outputs //
expect(result).toBe(false);
});
对于你的情况,很难说出要测试的最佳输出是什么,因为我们目前缺少很多上下文。实际上,您必须测试的输出取决于您期望从该函数中获得的行为。您只是期望图片网址发生变化吗?您是否也期望HTML结构保持不变? “回归假”也是一种期望吗?
对于你可以在HTML / DOM上进行的测试,它通常分4个步骤完成。您必须首先设置HTML,调用您的函数,测试输出,然后清理所有内容。如果你的一个期望是只需要更改图像的URL,它将如下所示:
it("URL of the image needs to change", function () {
// Step 1 - Setup the initial state of the HTML //
var baseHTML = '<div id="showImgContainer"><img src="test.j" id="showImg" /></div>';
var div = document.createElement("div");
div.innerHTML = baseHTML;
document.body.appendChild(div);
// Step 2 - Call //
showIMG();
// Step 3 - We check the state of the HTML with our expectation //
expect($("#showImgContainer img").attr("src")).toEqual("anothertest.jpg");
// Step 4 - Cleanup the setup //
document.body.removeChild(div);
});