简体   繁体   English

在将范围参数添加到范围时AngularJS测试错误?

[英]AngularJS testing error on adding name parameter to scope?

Error received when running karma start configs/karma.conf.js : 运行karma start configs/karma.conf.js时收到错误:

INFO [PhantomJS 1.9.2 (Linux)]: Connected on socket PK-IbFeI1qpFq0fix6WI
PhantomJS 1.9.2 (Linux) IndexController should add name parameter to scope FAILED
Error: [$injector:modulerr] http://errors.angularjs.org/1.2.6/$injector/modulerr?p0=myapp.controllers&p1=Error%3A%20%5B%24injector%3Anomod%5D%20http%3A%2F%2Ferrors.angularjs.org%2F1.2.6%2F%24injector%2Fnomod%3Fp0%3Dmyapp.controllers%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%3A9877%2Fbase%2Fpublic%2Fapp%2Flib%2Fangular%2Fangular.min.js%3F1387689655000%3A20%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%3A9877%2Fbase%2Fpublic%2Fapp%2Flib%2Fangular%2Fangular.min.js%3F1387689655000%3A21%0A%20%20%20%20at%20http%3A%2F%2Flocalhost%3A9877%2Fbase%2Fpublic%2Fapp%2Flib%2Fangular%2Fangular.min.js%3F1387689655000%3A29
    at /home/Projects/abbrevi8-karma-tests/public/app/lib/angular/angular.min.js:29
TypeError: 'undefined' is not an object (evaluating 'scope.name')
    at /home/Projects/abbrevi8-karma-tests/test/unit/controllerSpec.js:19
PhantomJS 1.9.2 (Linux): Executed 1 of 1 (1 FAILED) ERROR (0.178 secs / 0.006 secs)

public/app/controllers.js 公共/应用/ controllers.js

var myApp = angular.module('myApp', []);

myApp.controller('IndexController', function ($scope) {
        $scope.name = 'bob';
});

test/unit/controllerSpec.js 测试/单元/ controllerSpec.js

'use strict';

describe('IndexController', function() {
    //initialise module
    beforeEach(module('myapp.controllers'));

    //params initialised in scope for tests
    var ctrl, scope;

    beforeEach(inject(function($controller) {
        //get controller from $controller provider
        scope = {}; 
        ctrl = $controller('IndexController', {
            $scope: scope
        }); 
    }));

    it ('should add name parameter to scope', function() {
        expect(scope.name).toBeDefined(); 
    }); 
});

Full project (same as above, only with my karma.conf.js and setup.sh ): https://gist.github.com/AlecTaylor/8078807 完整项目(与上面相同,仅限于我的karma.conf.jssetup.sh ): httpskarma.conf.js

Try: 尝试:

beforeEach(module('myApp'));

instead of: 代替:

beforeEach(module('myapp.controllers'));

I'm just guessing here, as I don't have Phantom to run on Linux... but $scope is expected to be a Scope object. 我只是在这里猜测,因为我没有Phantom在Linux上运行......但是$scope预计会成为Scope对象。

Try injecting $rootScope , and either use that, or create a $new() child scope from it: 尝试注入$rootScope ,并使用它,或者从中创建$new()子范围:

beforeEach(inject(function($controller, $rootScope) {
    //get controller from $controller provider
    scope = $rootScope.$new(); 
    ctrl = $controller('IndexController', {
        $scope: scope
    }); 
}));

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

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