Zac*_*cho 6 jasmine angularjs gruntjs yeoman karma-runner
我有一个使用Angular Translate的应用程序(https://github.com/PascalPrecht/angular-translate).翻译通过浏览器在应用程序中运行良好,但当我尝试测试任何控制器时,我得到错误:意外请求:GET locale/locale-en.json.我如何对我的控制器进行单元测试,因为translate在启动时会对语言文件进行GET请求?
我正在使用与Karma的yeoman角度发生器.
App.js:
angular.module('myApp', ['ngCookies', 'ui.bootstrap', 'pascalprecht.translate'])
.config(function ($routeProvider, $locationProvider, $translateProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
$translateProvider.useStaticFilesLoader({
prefix: 'locale/locale-',
suffix: '.json'
});
$translateProvider.uses('en');
$translateProvider.useLocalStorage();
});
Run Code Online (Sandbox Code Playgroud)
控制器测试:
describe('Controller: DocumentationCtrl', function () {
// load the controller's module
beforeEach(module('myApp'));
var DocumentationCtrl,
scope,
$httpBackend;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope, $injector) {
$httpBackend = $injector.get('$httpBackend');
scope = $rootScope.$new();
DocumentationCtrl = $controller('DocumentationCtrl', {
$scope: scope
});
}));
it('should attach a list of awesomeThings to the scope', function () {
$httpBackend.whenGET('locale/locale-en.json').respond(200, {
"TITLE": 'My App'
});
expect(scope.awesomeThings.length).toBe(3);
});
});
Run Code Online (Sandbox Code Playgroud)
文档控制器只是标准生成的控制器.
您必须在配置阶段指定首选语言,而不是运行阶段.因此$translate.uses('us')
变得$translateProvider.preferredLanguage('us')
.同样如此useLocalStorage()
.这些都是配置$translate
服务的方法.
您还应该尽量避免uses()
设置默认语言.请preferredLanguage()
改用.原因是,$translate.uses()
尝试尽快加载i18n文件,如果有一个cookie或类似的使用另一种语言密钥,uses()
将加载两个文件,这就是为什么我们介绍了preferredLanguage()
,是的,这应该解决问题.