简体   繁体   English

Angular控制器未在茉莉花测试中初始化

[英]Angular controller not initialized in jasmine test

I ran into issues writing jasmine tests for an AngularJS application using angular ui-router. 我遇到了使用angular ui-router为AngularJS应用程序编写茉莉花测试的问题。 My services and app get initialized properly in the test, but the controllers do not start up properly. 我的服务和应用程序在测试中正确初始化,但是控制器无法正常启动。 I've taken the application in question out of the equation and reduced the problem to a simple one controller example that exhibits the same behavior. 我已经从等式中删除了有问题的应用程序,并将问题简化为一个表现出相同行为的简单控制器示例。 Here's the actual test code: 这是实际的测试代码:

describe('Test', function() {
    var async = new AsyncSpec(this);
    var scope = {};

    beforeEach(angular.mock.module('TestApp'));

    beforeEach(angular.mock.inject(function($rootScope, $state, $templateCache) {
        scope.$rootScope  = $rootScope;
        scope.$state      = $state;

        $templateCache.put('start.html', '<div class="start"></div>');
    }));

    async.it('Test that TestCtrl is initialized', function(done) {
        scope.$rootScope.status = { done: false };
        scope.$rootScope.$on('$stateChangeSuccess', function(event, state, params) {
            expect(scope.$rootScope.status.done).toBe(true);
            done();
        });
        scope.$state.transitionTo('start', {}, { notify: true });
        scope.$rootScope.$apply();
    });
});

Here's the complete runnable test 这是完整的可运行测试

The application gets initialized correctly, the ui router is able to transition the application to the correct state, but the controller does not get initialized. 应用程序已正确初始化,ui路由器能够将应用程序转换为正确的状态,但控制器未初始化。 I need the router to initialize the controllers as the router passes critical configuration to them. 当路由器将关键配置传递给它们时,我需要路由器初始化控制器。 I want to avoid duplicating that configuration in the tests. 我想避免在测试中重复该配置。

I must be missing something, but what? 我一定想念什么,但是呢? I appreciate any and all input, thanks! 感谢您提供的所有意见,谢谢!

You need to use the $controller service to instantiate your controller in your tests and pass it your scope. 您需要使用$ controller服务在测试中实例化控制器并将其传递给您的范围。 For example... 例如...

ctrl = $controller('TestCtrl', {$scope: scope});

Notice that I also moved the declaration of $rootScope.done to the TestCtrl to prevent an error about $rootScope.done being undefined. 注意,我还将$ rootScope.done的声明移到了TestCtrl上,以防止有关$ rootScope.done的错误被定义。 Here's the fiddle... 这是小提琴...

http://jsfiddle.net/C8QtB/3/ http://jsfiddle.net/C8QtB/3/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM