当我编写QUnit测试代码时,一个问题让我感到震惊。组织QUnit模块和QUnit测试(断言测试)的最佳方法是什么?以及如何定义QUnit模块和待测试函数之间的关系。
实际上,我通常将一个函数与一个原子模块相关联,一个QUnit模块与几个原子断言测试相关。代码如下。但它在工程项目中总是有效和实用吗?如果有一个原则来划分QUnit模块和QUnit测试?
我很感激您的回答!
//function 1
numberUnit: function (sValue) {
if (!sValue) {
return "";
}
return parseFloat(sValue).toFixed(2);
},
//function 2
priceState: function(iPrice){
if(iPrice < 50) {
return "Success";
}else if(iPrice >= 50 && iPrice < 250){
return "None";
}else if(iPrice >=250 && iPrice <2000){
return "Warning";
}else {
return "Error";
}
}
//module 1, related to function 1
QUnit.module("Number unit");
function numberUnitValueTestCase(assert, sValue, fExpectedNumber) {
// Act
var fNumber = formatter.numberUnit(sValue);
// Assert
assert.strictEqual(fNumber, fExpectedNumber, "The rounding was correct");
}
QUnit.test("Should round down a 3 digit number", function (assert) {
numberUnitValueTestCase.call(this, assert, "3.123", "3.12");
});
QUnit.test("Should round up a 3 digit number", function (assert) {
numberUnitValueTestCase.call(this, assert, "3.128", "3.13");
});
QUnit.test("Should round a negative number", function (assert) {
numberUnitValueTestCase.call(this, assert, "-3", "-3.00");
});
QUnit.test("Should round an empty string", function (assert) {
numberUnitValueTestCase.call(this, assert, "", "");
});
QUnit.test("Should round a zero", function (assert) {
numberUnitValueTestCase.call(this, assert, "0", "0.00");
});
//module 2, related to function 2
QUnit.module("Price State");
//priceStateTestCase, reduce codes repeatance
function priceStateTestCase(oOptions){
//act
var sState = formatter.priceState(oOptions.price);
//assert
oOptions.assert.strictEqual(sState,oOptions.expected, "The price state was correct!");
}
QUnit.test("Should format the products with a price lower than 50 to Success",function(assert){
priceStateTestCase.call(this,{
assert: assert,
price: 42,
expected: "Success"
});
});
QUnit.test("Should format the products with a price of 50 to Normal",function(assert){
priceStateTestCase.call(this,{
assert: assert,
price: 50,
expected: "None"
});
});
QUnit.test("Should format the products with a price between 50 and 250 to Normal",function(assert){
priceStateTestCase.call(this,{
assert: assert,
price: 134,
expected: "None"
});
});