2016-03-01 41 views
0

我正在爲需要一些相當複雜的json對象的項目編寫單元測試。它們變得太冗長以至於無法插入spec文件,我想將本地json文件導入到我的測試中。我已經嘗試了多種解決方案並不真正爲這個項目工作: Loading a mock JSON file within Karma+AngularJS test Angular-Jasmine, loading json How to load external Json file using karma+Jasmine for angularJS testing?/ 和使用JavaScript與XMLHttpRequest() .... 什麼是正確的方式去加載外部文件到規範,而無需創建新的依賴關係?單元測試:AngularJS + Karma + Jasmine,加載本地JSON

回答

0

我認爲在您的案例中測試的最佳方式是使用$httpBackend。它允許使用您的$resource$http併爲他們提供測試數據。

如果你要處理大量json對象,你可以在單獨的js文件中定義它們(函數),包括這些文件在您的測試JS包,只是調用這些函數來回報您的json當你設置$httpBackend服務。 希望這有助於。

更新 由於測試只是普通的老js,您可以創建一個單獨的js文件。並在其中聲明一個函數,它將返回你的json。

(function (window) { 
    'use strict'; 

    if (!window.myJsonMocks){ 
     window.myJsonMocks = {}; //creating the object that will contain all the functions with json 
    } 

    window.myJsonMocks.myCustomersQueryResultJson = function(){ 
     return '{"value":[{"CategoryInfo":{"Id":1,"Type":1},"Caption":"Test","Path":"1/#/1"},{"CategoryInfo":{"Id":2,"Type":1},"Caption":"new","Path":"2/#/2"},{"CategoryInfo":{"Id":3,"Type":2},"Caption":"Another one","Path":"3/#/3"}]}' 
    }; 
})(window); 

既然你聲明爲IIFE它將註冊在全球範圍內的功能,因此,這將是在測試中使用。只要確保在測試場景之前包含它。然後你只需撥打

$httpBackend.when('GET', 'api/customerssdata').respond(window.myJsonMocks.myCustomersQueryResultJson()); 
+0

是的,我使用$ httpBackend來模擬其餘的API。我認爲你是正確的,但你能提供一個例子嗎? – arturobelano

+0

是的,仍然有點困惑。我通過我的karma配置文件包含了js文件,但是如何將該JavaScript文件注入到我的規範中? – arturobelano

+0

完美答案,非常感謝。 – arturobelano

相關問題