Karma-Jasmine:如何测试$ translate.use?

时间:2015-10-22 08:46:13

标签: javascript angularjs jasmine karma-runner karma-jasmine

情况:

我正在测试允许用户选择语言的功能。 但我收到以下错误:

TypeError: $translate.use is not a function

我在SO和其他论坛上看到过类似的问题,但它们对我不起作用。

代码:

配置:

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?

1 个答案:

答案 0 :(得分:3)

我认为$translate不是你的方法而你不需要测试它,那么你可以用noop方法返回一个对象

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");
    });
});

如果您需要检查是否可以使用正确的参数调用

$translate = {
  use: jasmine.createSpy('$translate.use')
}

然后你可以把它添加到期望

expect($translate.use).toHaveBeenCalledWith(//language code)