2014-03-14 205 views
0

我试图测试我的控制器时遇到问题。AngularJS单元测试控制器

我只是把代码放在这里和之后,解释问题是什么。

控制器

// Controller name is handy for logging 
var controllerId = 'splash'; 

// Define the controller on the module. 
// Inject the dependencies. 
// Point to the controller definition function. 
angular.module('app').controller(controllerId, 
    ['$scope', 'datacontext', splash]); 

function splash($scope, datacontext) { 
    // Using 'Controller As' syntax, so we assign this to the vm variable (for viewmodel). 
    var vm = this; 

    // Bindable properties and functions are placed on vm. 
    vm.activate = activate; 
    vm.title = 'Splash'; 
    vm.getRooms = function() { 
     return vm.rooms; 
    } 
    activate(); 
    return vm; 
    function activate() { 
     datacontext.getRooms().then(function (data) { 
      vm.rooms = data; 
     }); 

    } 
} 

DataContext的方法

function getRooms() { 
     var deferred = Q.defer(); 
     deferred.resolve([{ id: 1, Name: "A02" }, { id: 2, Name: "A03" }]); 
     return deferred.promise; 
    } 

测试

it('should have a splash title', inject(function($q, datacontextMock) { 
    var vm = testContext.$controller('splash', { $scope: scope, datacontext: datacontextMock }); 

    expect(vm.title).toEqual('Splash'); 
    expect(vm.rooms).not.toBeNull(); 

    console.log(vm); 
    expect(vm.rooms).toEqual(testContext.rooms); 
})); 

问题是,测试失败。 它会告诉我,vm.rooms是未定义的......但事实并非如此。 当用console.log记录vm时,我实际上可以通过点击vm对象并在那里看到一个房间数组,它是datacontext返回的数组。

为什么这告诉我vm.rooms是未定义的?

回答

1

解决了它。 结束使用$ q而不是Q(无论如何,这是建议,但似乎没有工作之前)。

此外,在测试中,我现在必须激活方法在控制器上像这样的电话:

scope.$digest(vm.activate()); 

这解决了这个问题对我来说。