首頁  >  文章  >  web前端  >  kmock javascript 单元测试代码_javascript技巧

kmock javascript 单元测试代码_javascript技巧

WBOY
WBOY原創
2016-05-16 18:10:591170瀏覽
复制代码 代码如下:

(function () {
var KMock = window.KMock = function () {

}
KMock.prototype.setup = function (methodName) {
var instance = this;

instance[methodName] = {
returnAs: function (fn) {
instance["_" + methodName] = function () {
instance[methodName].invokeNum++;
fn.call();
}
},
isVerify: function (exceptNum) {
if (exceptNum != null) {
return exceptNum == instance[methodName].invokeNum;
}
else {
return instance[methodName].invokeNum > 0;
}
},
invoke: function () {
instance["_" + methodName].call();
},

invokeNum: 0
};
return instance[methodName];
}


})();

//自己写了个mock类,暂时是用来模拟函数,然后判断函数的调用次数,以下是用法

/// <reference path="Flight.js"></reference> <br>/// <reference path="http://demo.jb51.net/jslib/qunit/qunit.js"></reference> <br>/// <reference path="KMock.js"></reference> <br><br><br>module("enter coin"); <br><br>test("enter coin while game has not yet start", function () { <br>var flight = new KFlight(); <br><br>var mock = new KMock(); <br>mock.setup("draw").returnAs(function () { <br>}); <br><br>flight.draw = mock.draw.invoke; <br><br><br>equal(flight.coinNum, 0); <br>equal(flight.gameState, 0); <br>flight.coinEnter(); <br>equal(flight.coinNum, 0); <br>equal(flight.gameState, 1); <br><br><br>equal(mock.draw.isVerify(1), true); <br><br>});<br>
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn