如何在工厂中为变量赋值并使用AngularJS中的赋值测试方法?

时间:2015-01-23 08:52:21

标签: angularjs unit-testing jasmine karma-jasmine angularjs-factory

我有以下工厂。为简洁起见,我更改了init方法,因为所有重要的是它在teamsConfig中加载json数据(类似于测试中的数据)。

var AppController = angular.module("AppController");
AppController.factory('TeamFactory', ['$http', '$q',
                           function($http, $q) {

var teamsConfig = {};
return{
        init: function() {
                $http.get('navigation/TeamsConfiguration.json').success(function(data) {
                teamsConfig = data;
            }).error(function(msg, code) {
            deferred.reject(msg);
        });

    return deferred.promise;
    },

        getCaptainName: function(team) {
        return teamsConfig[team].captainName;
    }

};

我的Jasmine代码如下

describe('Test TeamCaptain',function(){
beforeEach(module('AppController'));
var ctrl,scope,http,route, routeParams,location,q,svc,factory;
beforeEach(inject(function(TeamFactory,$rootScope){
    scope = $rootScope.$new();
    TeamFactory.teamsConfig = {
            "India":
            {
            "captain": "Dhoni",
            "batsman": "Kohli"
            },
            "Australia":
            {
            "captain": "Clarke",
            "batsman": "Watson"
            }
        };

         factory = TeamFactory;
         }));
     it('should get the captain of the team.',function(){
         var captain= '';
         var team = 'India';
         captain = factory.getCaptainName(team);
         expect(captain).toEqual('Dhoni');
    });
}));

在运行测试时,我收到错误 --TypeError:' undefined'不是评估teamConfig [team] .captainName'

的对象

我已将代码更改为原始代码,可能会出现小错误/拼写错误。

0 个答案:

没有答案