使用Titanium做單元測(cè)試
總之,為了在Titanium的控制臺(tái)輸出Log,Titanium.API.info和Titanium.API.error等能測(cè)試輸出就可以了。
這回我們?cè)囍褂肬nit系中流行的QUnit和BDD系的Jasmine。
使用QUnit
Titanium使用的Adapter已經(jīng)在GitHub上公開了。
lukaso/qunit–GitHub
在自己的Project使用的時(shí)候,Resources文件夾下保存一下文件就可以了。
*runner.js
*qunit/qunit.js
*qunit/titanium_adaptor.js
*test/tests_to_run.js
然后,在test/tests_to_run.js中寫測(cè)試內(nèi)容。在app.js的任何位置把runner.js文件include后運(yùn)行即可。
查看titanium_adaptor.js的內(nèi)容,我們可以看到,它做的事情就是利用QUnit的Logging處理把Log輸出到Titanium的控制臺(tái)上。
所以想輸出的時(shí)候,按照喜歡的改寫也是不難的事情。
在app.js中添加代碼確認(rèn)動(dòng)作
app.js_snippet中,Tabgroup中追加單元測(cè)試用的Tab,只是簡(jiǎn)單的確認(rèn),單純的在app.js的末尾追加一下行即可測(cè)試動(dòng)作:
Js代碼
- Titanium.include('runner.js');
確認(rèn)動(dòng)作的test/tests_to_run.js
為了確認(rèn)動(dòng)作,什么測(cè)試也沒有寫,只是測(cè)試QUnit的動(dòng)作的例子代碼:
- module("QUnitonTitanium");
- test("OKtest(pass)",function(){
- ok(true);
- }
- );
- test("equaltest(nopass)",function(){
- equal('hogehoge','hige');
- }
- );
動(dòng)作結(jié)果會(huì)很好的輸出到Titanium的控制臺(tái)上。
順便說一下,由于結(jié)果中包含了HTML代碼,很難理解。使用QUnit-TAP不是很好。
使用Jasmine
Jasmine中,能夠自定義測(cè)試出力的Reporter,所以可以做成Titanium用的Reporter。
jasmine.js中,提供了基本的Reporter類,可以根據(jù)它做成自己的Reporter類。
實(shí)際編碼的時(shí)候可以參考Jasmine官方發(fā)布版本中的jasmin-html.js和jasmine.console_reporter.js。
包含了很好出力的Reporter的JasmineTitanium也已經(jīng)公開了。
在app.js中添加代碼確認(rèn)動(dòng)作
還沒有任何測(cè)試內(nèi)容,只是確認(rèn)Jasmine動(dòng)作的例子代碼。
前提是在Resorses/jasmine中,jasmine.js和jasmine-titanium.js(上邊的TitaniumReporter)
Js代碼
- Ti.include('jasmine/jasmine.js');
- Ti.include('jasmine/jasmine-titanium.js');
- describe("JasmineSample",function(){
- it("pass!",function(){
- varfoo=2;
- expect(foo).toEqual(2);
- }
- );
- });
- describe("SecondJasmineSample",function(){
- it("fail!",function(){
- varfoo=1;
- expect(foo).toEqual(2);
- }
- );
- });
- jasmine.getEnv().addReporter(newjasmine.TitaniumReporter());
- jasmine.getEnv().execute();
執(zhí)行結(jié)束后,就能看到失敗的測(cè)試和合計(jì)結(jié)果。
實(shí)際的開發(fā)中,應(yīng)該把測(cè)試代碼統(tǒng)一放在spec文件夾中比較好。
注:
沒有spec文件夾或者文件夾為空是不能啟動(dòng)的。