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

Karma-Jasmine: How to test $translate.use?

情况:

我正在测试允许用户select一种语言的功能。 但是我收到以下错误:

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?

我假设 $translate 不是你的方法,你不需要测试它,那么你可以 return 一个带有 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)