单元测试使用$过滤器控制器功能(“翻译”)
问题描述:
我有它返回一个字符串拼接与翻译过滤器的返回值的控制器功能:
$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');
});
答
我会嘲笑$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');
});
});
在哪里,以及如何为角翻译配置? –
看到我的编辑,我实际上在beforeEach中添加了$ httpBackend.expectGET('assets/locale/en_gb.json'),但我不确定如何将响应属性设置为对该json文件的实际响应。 – mindparse
最简单的方法是使用https://www.npmjs.com/package/karma-ng-json2js-preprocessor定义包含json文件的角常量,并使用测试模块配置带这些常量的angular-translate,而不是一个静态文件加载器。没有http请求嘲笑了,并且你的真实文件被使用 –