【问题标题】:Trying to test Angular with Karma/Jasmine, but can't get the Jasmine tests to set $scope correctly尝试使用 Karma/Jasmine 测试 Angular,但无法让 Jasmine 测试正确设置 $scope
【发布时间】:2014-11-15 07:29:00
【问题描述】:

我的 Angular 脚本如下所示:

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



app.controller('TestController', function ($scope) {
    $scope.test= "TEST";
});

我的测试文件如下所示:

describe('first test', function() {
 var $scope;

  beforeEach(function (){
    module('myApp');

    inject(function($rootScope, $controller) {
        $scope = $rootScope.$new();
        ctrl = $controller('TestController', {
            $scope: $scope
        });
    });
  it('scope should have test', function() {
    expect($scope.test).toEqual("TEST");
  });
});

此测试失败,提示 $scope.test 未定义。我在 Chrome 中调试,发现 $scope 上有一堆属性,但没有一个是测试的。我在网上浏览了几个示例,它们看起来都与此非常相似。我不太确定我在这里做错了什么,我被卡住了....

编辑 我尝试添加 $controller 来注入,但我仍然遇到同样的问题。

【问题讨论】:

  • 你认为你会在哪里得到$controller

标签: javascript angularjs unit-testing jasmine


【解决方案1】:

您需要将$controller service$rootScope 一起传递:

inject(function($rootScope, $controller) {
    $scope = $rootScope.$new();
    ctrl = $controller('TestController', {
        $scope: $scope
    });
});

【讨论】:

  • 添加 $controller 后我仍然遇到同样的问题
  • 调试时是否检查了控制器代码是否执行? (在控制器定义中添加console.log并验证)
  • 不,不是。我看到 var app = "..." 正在运行,但我的控制器代码没有
  • @user3715648 仅供参考,我已经复制了您遇到的问题,添加$controller 为我解决了它。然后,我发布了一个答案。
  • @alecxe 我试着复制你的答案,但我仍然遇到同样的问题。
猜你喜欢
  • 2015-12-07
  • 1970-01-01
  • 2018-01-31
  • 2018-10-25
  • 2015-12-10
  • 1970-01-01
  • 1970-01-01
  • 2017-06-10
相关资源
最近更新 更多