Karma-Jasmine:如何测试$ translate.use? [英] Karma-Jasmine: How to test $translate.use?
问题描述
情况:
我正在测试允许用户选择语言的功能。
但我收到以下错误:
I am testing the function that allow the user to select a language. But I am getting the following error:
TypeError: $translate.use is not a function
我在SO和其他论坛上看到过类似的问题,但它们对我不起作用。
I have seen similar questions in SO and other forums but they are not working for me.
代码:
配置:
app.config(function($stateProvider, $urlRouterProvider, $translateProvider) {
$translateProvider.useSanitizeValueStrategy('sanitize');
$translateProvider.translations('EN', {
"MY_ACCOUNT": "My account",
"PROJECT_LIST": "Project List",
"SETTINGS": "Settings",
});
$translateProvider.translations("IT", {
"MY_ACCOUNT": "Mio account",
"PROJECT_LIST": "Lista progetti",
"SETTINGS": "Impostazioni",
});
$translateProvider.preferredLanguage(window.localStorage['language'] || 'EN');
$translateProvider.fallbackLanguage("EN");
功能:
$scope.select_language = function(language)
{
window.localStorage['language_code'] = language.code;
$translate.use(language.code);
$rootScope.app_language = language.code;
}
测试:
describe('App tests', function() {
beforeEach(module('my_app.controllers'));
beforeEach(inject(function(_$controller_, _$rootScope_)
{
$controller = _$controller_;
$rootScope = _$rootScope_;
$scope = _$rootScope_.$new();
$translate = {};
var controller = $controller('MainCtrl', { $scope: $scope, $rootScope: $rootScope, $translate: $translate });
}));
describe('Language tests', function()
{
it('should properly load select_language function', function()
{
$scope.select_language({ name: "italiano", url: "img/italy.png", code: "IT"});
expect($rootScope.app_language).toEqual("IT");
});
});
问题:
为什么我收到错误?
如何正确测试$ translate.use?
How can I properly test $translate.use?
推荐答案
我认为 $ translate
不是你的方法而且你不喜欢不需要测试它,然后你可以用noop方法返回一个对象
I assume that the $translate
is not your methods and you don't need to test it, then you can return an object with noop method
describe('App tests', function() {
beforeEach(module('my_app.controllers'));
beforeEach(inject(function(_$controller_, _$rootScope_)
{
$controller = _$controller_;
$rootScope = _$rootScope_;
$scope = _$rootScope_.$new();
$translate = {
use: function(){}
};
var controller = $controller('MainCtrl', { $scope: $scope, $rootScope: $rootScope, $translate: $translate });
}));
describe('Language tests', function()
{
it('should properly load select_language function', function()
{
$scope.select_language({ name: "italiano", url: "img/italy.png", code: "IT"});
expect($rootScope.app_language).toEqual("IT");
});
});
如果你需要检查是否用正确的参数调用它你可以做
and if you need to checkout if it's called with correct parameters you can do
$translate = {
use: jasmine.createSpy('$translate.use')
}
然后你可以把它添加到期望值
then you can add it to expectations
expect($translate.use).toHaveBeenCalledWith(//language code)
这篇关于Karma-Jasmine:如何测试$ translate.use?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!