【问题标题】:How to test $scope in Jasmine test?如何在 Jasmine 测试中测试 $scope?
【发布时间】:2016-09-14 14:47:20
【问题描述】:

我尝试使用 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 位于我的 jasmine 调试页面的 index.html 中,还有带有测试的脚本。

我发现如果我删除 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

【问题讨论】:

  • 如果expect(true).toBe(true); 确实失败了,则表明beforeEach() 中出现了错误。你能检查一下浏览器开发工具来确定吗?
  • 这是一个错误pastebin.com/BSwtJpc7

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


【解决方案1】:

检查您的模块依赖项。可能你的依赖项之一没有加载到 karma 配置文件部分,所以你的模块创建失败。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-15
    • 1970-01-01
    • 2021-04-08
    • 1970-01-01
    • 2021-06-08
    • 2011-12-02
    相关资源
    最近更新 更多