为什么我的Angular test $ scope没有定义方法呢?

时间:2013-12-02 12:09:04

标签: javascript angularjs dependency-injection requirejs jasmine

由于某种原因,我注入的范围没有填充,实际上这可能有点明显,console.log语句显示控制器实际上没有被执行,直到测试运行,但我我不确定为什么或如何解决它。 更新:,我转储Insert,它似乎是一个空对象,这可能不是正确的事情......

define([
'angular-mocks',
'controllers/insert'],
function( mocks ) {
'use strict';

describe('Controller: Insert', function () {
    // load the controller's module
    beforeEach(module('pasteyApp'));

    var Insert,scope,location,pastes;

    // Initialize the controller and a mock scope
    beforeEach(inject(function ( $injector, $controller, $rootScope ) {
        pastes     = $injector.get('pastes');
        location   = $injector.get('$location');
        scope      = $rootScope.$new();
        scope.code = 'package Foo::Bar;',
        Insert     = $controller('Insert', {
            $scope:    scope,
            $location: location,
            pastes:    pastes,
        });
    }));


    it('has code', function () {
        expect( scope.code ).toBe('package Foo::Bar;');
        scope.$apply();
    });

    it('updates location', function () {
        scope.view();
        expect( location.path() ).not.toBe('');
        expect( location.path() ).toBe('...');
        expect( pastes ).toBe( {} );
    });
});

});

conrollers/insert

define([
'crypto.MD5',
'angular',
'services',
], function() {
'use strict';

return ['$scope', '$location', 'pastes', function ( $scope, $location, pastes ) {
    $scope.view = function( ) {
        if ( $scope.code ) {
            // boo hex, really want urlsafe base64
            var digest = Crypto.MD5( $scope.code ).toString();
            console.log( digest );
            pastes[digest] = $scope.code;
        }
        $location.path( digest );
    };
}];
});

controllers

define([
    'app',
    'services',
], function ( app ) {
    'use strict';


    return app
            .controller('Insert', ['$scope','$injector', function( $scope, $injector ) {
                    require(['controllers/insert'], function( insert ) {
                            $injector.invoke( insert, this, { '$scope': $scope });
                    })
            }])
            .controller('Render', ['$scope','$injector', function( $scope, $injector ) {
                    require(['controllers/render'], function( render ) {
                            $injector.invoke( render, this, { '$scope': $scope });
                    });
            }])
            ;
});

实际错误

Chrome 31.0.1650 (Linux) Controller: Insert updates location FAILED
    TypeError: Object #<Scope> has no method 'view'
        at null.<anonymous>   (/home/xenoterracide/dev/Pastey/test/spec/controllers/insert.js:33:10)

1 个答案:

答案 0 :(得分:1)

我想我理解你的问题。由于require()是异步的并且您的Jasmine测试不是,因此在您的规范运行时尚未执行'require / insert'功能。在执行it()块之前,您需要在Jasmine中找到一种等待require完成的方法。

这就是控制器是一个对象的原因,但它还没有。您正在清楚地注册所有内容(否则$controller()会抛出),但不能等待require.js完成其工作。

看起来this question可以很好地处理您需要做的事情。