2014-09-29 179 views
0

如果我正在测试为表单编写的验证函数,测试方法在QUnit中的外观如何?再说了,如果表单需要检查名称字段不为空,我的功能测试这个功能貌似QUnit测试测试用例

function validNameCheck(form) 
{ 
    if (document.forms["formSecond"]["nameFull"].value=="") 
    { 
    alert("Name Field cannot be empty") 
    return false; 
    } 
    else 
    return true; 
} 

这将是一个可能的QUnit测试用例上面?

+0

的参数'form'似乎是没用过 – 2014-09-29 15:49:52

回答

0

比方说,要传递给validNameCheck函数的参数是一个form要检查是否为空或不,我的意思是这样的name元素:

var myName = document.forms["formSecond"]["nameFull"]; 

然后你的函数应该看起来像这样:

function validNameCheck(form){ 
    if (form.value==""){ 
     alert("Name Field cannot be empty") 
     return false; 
    }else{ 
     return true; 
    } 
} 

请注意,我会更改您正在检查的硬编码元素。

然后你QUnit的测试应该是这样的:

QUnit.test("CheckingName", function(assert) { 
    var value = false; 
    assert.equal(value, validNameCheck(myName), "We expect the return to be false"); 
}); 
0

我想借此@ Gepser的解决方案远一点(但可以肯定的是解决方案的一部分)。如果您想通过名称获取表单,那么您可能希望在每次测试之前使用QUnit的夹具来重置HTML。那么你可能想要剔除alert方法,以便在测试时不会得到一堆。

在QUnit HTML文件:

<body> 
    <div id="qunit"></div> 
    <div id="qunit-fixture"> 
    <!-- Anything in here gets reset before each test --> 
    <form name="formSecond"> 
     <input type="text" name="nameFull"> 
    </form> 
    </div> 
    ... 
</body> 

然后在你的QUnit测试(无论是在HTML文件中我们在自己的JS文件):

QUnit.begin(function() { 
    // mock out the alert method to test that it was called without actually getting an alert 
    window.alert = function() { 
    window.alert.called++; 
    }; 
    window.alert.called = 0; 
}); 
QUnit.testDone(function() { 
    // reset the alert called count after each test 
    window.alert.called = 0; 
}); 

... 

// From @Gepser's answer... 
QUnit.test("CheckingName", function(assert) { 
    var value = false; 
    assert.equal(value, validNameCheck(), "We expect the return to be false"); 
    // add an assertion to make sure alert was called 
    assert.equal(1, window.alert.called, "alert was called only once"); 
});