標籤:服務 hid play stl exp function lan open ted
條件與目標:
- 前端使用AngularJS,介面服務均使用$http訪問。
- 與後台協商好介面,完全獨立並行開發,不用等待後台開發完介面才能進行頁面測試。
- 需要gulp打包系統參與,即打包之前可以類比後台介面測試,而打包之後則為Release版本,需要真實後台服務參與。
- 雖不能包括所有情況,但大部分基於資料的情境都可實用。
實踐方法:
- 在index.html中建立gulp打包區塊,以<!--build:js js/app.min.js-->開始,以<!--/build-->結束。
- 在index.html中引用angular-mocks.js(類比http資料返回外掛程式)。
- 建立testapi/mockinit.js(用於初始化資料類比架構),代碼如下:
angular.module(‘mocktest‘,[‘ngMockE2E‘]).run(function($httpBackend){ var http=$httpBackend; //pass http.whenGET(/ *.html/).passThrough(); http.whenGET(/ *.js/).passThrough(); http.whenGET(/ *.css/).passThrough(); http.whenGET(/ *.jpg/).passThrough(); //testlogin http.whenPOST(APPURL+‘/service/user/login‘).respond(function(m,url,data){ var param = angular.fromJson(data); var ret = {"result":-1,"message":"測試密碼錯誤"}; } return [200,ret]; });});View Code
- 根據功能建立其它測試模組,如testapi/moudlexxxmock.js:
angular.module(‘mocktest‘).run(function($httpBackend){ var http=$httpBackend; //test http.whenPOST(new RegExp(APPURL+‘/service/user/add‘)).respond(function(m,url,data){ var ret = {"result":0,"message":""}; return [200,ret]; });});View Code
- 在index.html 打包區塊中,引用所有的testapi目錄下的js檔案:
<script src="testapi/mockinit.js"></script> <script src="testapi/moduleusermock.js"></script> <script src="testapi/modulexxxmock.js"></script>
View Code
- 將此工程放入web容器中,運行未打包的程式,測試所有頁面與返回資料的處理邏輯,此時已不需要後台web服務參與。
- 建立一個空的Mockjs,如gulpmock.js,代碼如下:
angular.module(‘mocktest‘,[]);
- gulpfile中,在打包js時,不打包testapi中的js,而打包gulpmock.js,產生的app.min.js中已沒有類比的後台介面,直接使用後台服務介面。
結論:
雖然不知此方法是否為違背mock的初衷,但確實在獨立開發與獨立測試中取得較好的效果,非AngularJS工程可參考 Mockjax。
WebUI實踐之使用AngularJS 進行獨立開發(類比後台)