2012-12-25 26 views
3

我想测试我的功能,html是这样的。如何用html测试

这是我的功能。关于如何测试这个函数的好主意,用代码将会更有帮助。

<div id="showImgContainer"><img src="test.j" id="showImg" /></div> 

    function showIMG(){ 
     $('#showImg').remove(); 
     $('#showImgContainer').append('<img src="anothertest.jpg" />'); 
     return false; 
    } 
+1

您想要测试什么?你可以说得更详细点吗? –

回答

1

当你想做一个测试用例时,你必须指定的是输入和预期输出。茉莉花是通过以下方式

it("name of your test case", function() { 

    // Your call with the inputs // 
    var result = showIMG(); 

    // The expected outputs // 
    expect(result).toBe(false); 
}); 

对于您的情况下,很难说什么是测试的最佳输出为代表,因为我们目前缺乏大量的上下文。实际上,您必须测试的输出取决于您对函数期望的行为。你只是期待图像的URL改变?你是否也期待HTML结构保持不变? “回报虚假”也是一种期待吗?

为了测试你可以在HTML/DOM上做什么,它通常分4步完成。你必须首先完成HTML的设置,调用你的函数,测试输出,然后清理所有内容。如果您的期望之一是图片的网址需要更改,则看起来像这样:

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); 
}); 
+0

非常感谢!我会用渺小的方式来设置它 –