如何在Jasmine测试中测试$ scope?

时间:2016-05-18 08:27:33

标签: angularjs unit-testing jasmine karma-jasmine angular-mock

我试图用Jasmine为Angularjs编写单元测试。 这是我的控制器:

function HomeController($scope, fav, news, materials) {
    console.log('home controller');
    $scope.testMe = true;
}

module.controller('HomeController', HomeController);

并且测试

describe('Home controller tests', function() {
    var $rootScope, $scope, controller;

    beforeEach(function() {
        module('ap.designer');

        inject(function($injector) {
            $rootScope = $injector.get('$rootScope');
            $scope = $rootScope.new();
            controller = $injector.get('$controller')('HomeController', {$scope: $scope});
        });
    });

    describe('test controller functions', function() {
        it('Should return true', function() {
            expect($scope.testMe).toBe(true);
        });
     });
});

即使我尝试测试 expect(true).toBe(true),测试也失败了;

Jasmine,Karma,Angular和Angular-mocks在我的index.html中的jasmine调试页面中,脚本也带有测试。

我发现如果删除 beforeEach()块, expect(true).toBe(true)就会传递。

这是一个错误:

minErr/<@http://localhost:9876/base/bower_components/angular/angular.js:68:12
forEach@http://localhost:9876/base/bower_components/angular/angular.js:322:11
loadModules@http://localhost:9876/base/bower_components/angular/angular.js:4548:5
createInjector@http://localhost:9876/base/bower_components/angular/angular.js:4470:19
workFn@http://localhost:9876/base/bower_components/angular-mocks/angular-mocks.js:2954:44
angular.mock.inject@http://localhost:9876/base/bower_components/angular-mocks/angular-mocks.js:2934:35
@http://localhost:9876/base/src/js/modules/ap.designer/test/controllers/home/HomeControllerSpec.js:12:9
window.__karma__.loaded@http://localhost:9876/debug.html:42:9
@http://localhost:9876/debug.html:78:5

1 个答案:

答案 0 :(得分:0)

检查您的模块依赖关系。也许您的某个依赖项没有加载到karma配置文件部分,因此您的模块创建失败。