2015-09-04 79 views
0

我有它返回一個字符串拼接與翻譯過濾器的返回值的控制器功能:

$scope.getDetails = function(history) { 
    return angular.fromJson(history.value).name + $filter('translate')('CATALOGUE_HISTORY.ADD_ACTION'); 
}; 

我現在寫一個測試檢查函數返回預期的字符串,迄今已整理出以下:

'use strict'; 
    describe('CatalogueHistoryController', function() { 
     var $controller, $filter, $scope, controller, history; 

     beforeEach(function() { 
     module('app'); 
     }); 
     beforeEach(inject(function(_$controller_, _$filter_) { 
     $controller = _$controller_; 
     $filter = _$filter_; 
     })); 
     beforeEach(function() { 
     $scope = {}; 
     $httpBackend.expectGET('assets/locale/en_gb.json').respond({}) 
     controller = $controller('CatalogueHistoryController', { 
      $scope: $scope, 
      $filter: $filter 
     }); 
     }); 
     describe('$scope.getDetails', function() { 
     beforeEach(function() { 
      history = { 
      value: "{\"id\":3,\"name\":\"Some Name\"}" 
      }; 
     }); 
     it('should produce an add message', function() { 
      expect($scope.getDetails(history)).toEqual('Some Name was added to the catalogue'); 
     }); 
     }); 
    }); 

當測試運行時,它失敗:

預計「一些NameCATALOGUE_HISTO RY.ADD_ACTION'等於'某個名稱已添加到目錄'。

我是否需要以特定的CATALOGUE_HISTORY.ADD_ACTION ID的某種方式來模擬翻譯過濾器?

編輯

我目前配置的角度轉換,像這樣:

angular.module('app').config(function($translateProvider) { 
    $translateProvider.useStaticFilesLoader({ 
    prefix: 'assets/locale/', 
    suffix: '.json' 
    }); 
    $translateProvider.preferredLanguage('en_gb'); 
    $translateProvider.useSanitizeValueStrategy('sanitize'); 
}); 
+0

在哪裏,以及如何爲角翻譯配置? –

+0

看到我的編輯,我實際上在beforeEach中添加了$ httpBackend.expectGET('assets/locale/en_gb.json'),但我不確定如何將響應屬性設置爲對該json文件的實際響應。 – mindparse

+0

最簡單的方法是使用https://www.npmjs.com/package/karma-ng-json2js-preprocessor定義包含json文件的角常量,並使用測試模塊配置帶這些常量的angular-translate,而不是一個靜態文件加載器。沒有http請求嘲笑了,並且你的真實文件被使用 –

回答

1

我會嘲笑$filter並注入它的嘲笑版本。

您在此特定測試中的目標是測試您自己的功能,而不是測試過濾器。過濾器測試屬於過濾器實現。

可以說有很多方法來模擬過濾器,here's one關於翻譯過濾器本身。

一旦你確保無論何時調用測試$filter('translate')('has been entered');它只是返回你把這個字符串(即'has been entered'在這種情況下)你的測試將是一樣簡單:

describe('$scope.getDetails', function() { 
    beforeEach(function() { 
     history = { 
     value: "{\"id\":3,\"name\":\"Some Name\"}" 
     }; 
    }); 
    it('should produce an add message', function() { 
     expect($scope.getDetails(history)).toEqual('Some Name has been entered'); 
    }); 
    });