Javascript 模拟AngularJS控制器中的$state更改

Javascript 模拟AngularJS控制器中的$state更改,javascript,angularjs,unit-testing,karma-runner,Javascript,Angularjs,Unit Testing,Karma Runner,主模块注入了一切 require('./dashboard'); module.exports = angular.module('college', ['college.dashboard']) .config(function ($stateProvider) { $stateProvider .state('college.list', { url: '/college', t

主模块注入了一切

require('./dashboard');
module.exports = angular.module('college', ['college.dashboard'])

    .config(function ($stateProvider) {
        $stateProvider
            .state('college.list', {
                url: '/college',
                templateUrl: '/dashboard/dashboard.html',
                controller: 'DashboardCtrl',
                authenticate: true
            });
    })
    .factory('ProjectFactory', require('./services/college.service'));        
学院索引,使仪表板控制器可用

module.exports = angular.module('college.dashboard', 
  [])
    .controller('DashboardCtrl', require('./dashboard.controller.js'));
学院管理员公开了以下方法:

    module.exports = function($scope, $rootScope, $state) {

         $scope.openCollege = function(id) {       
            $rootScope.currentCollege = id;
            $state.go('college.main', {currentCollege: id});
        };
   };
单元测试调用时引发以下错误

scope.openCollege (2);
错误:

 Error: Could not resolve 'college.main' from state ''
创造国家

beforeEach(inject(function ($rootScope, $state, $location, $controller) {
        scope = $rootScope.$new();
        location = $location;
        rootScope = $rootScope;
        $rootScope.currentCollege = {};// Empty by default
        state = $state;            

        $controller('DashboardCtrl', {
            $scope: scope,
            $state: state,
            $location: location
        });

    }));
一些规范测试代码

 expect(state.current.name).to.equal('');
 scope.openCollege(2);
我需要弄清楚如何在Karma单元测试期间处理/模拟$state.go,以便state了解college.main

感谢您的帮助

你应该使用

it('should be able to go to person edit state', function () {
    DashboardCtrl();
    scope.openProject('12345');
    scope.$digest();
    expect(state.go).toHaveBeenCalledWith('college.main', { id : '12345' });
});

下面是我如何让它工作的

我在规范测试中添加了以下内容:

// Globally defined
var stateSpy;

// within the beforeEach
stateSpy = sinon.stub($state, 'go');

// In the unit test
scope.openCollege (2);
assert(stateSpy.withArgs('college.main', '{currentCollege: 2}').calledOnce);
注意:$状态未传递给控制器

我现在有绿色测试

谢谢你的帮助,给了我如何使这项工作的想法


J

问题是调用方法openCollege(2)返回错误“无法解决”college.main“”。此状态由这些模块之外的另一个模块设置。我只是想嘲弄一下。你以前有没有试过用spyOn?这对mespyOn(州“go”)来说很好。。。谢谢你能分享你的测试代码吗?您是否已将$state注入测试模块?添加了一些beforeach逻辑。这是我需要通过的最后一个测试…所有其他测试都通过了。