简体   繁体   English

尝试使用Karma / Jasmine测试Angular,但无法通过Jasmine测试正确设置$ scope

[英]Trying to test Angular with Karma/Jasmine, but can't get the Jasmine tests to set $scope correctly

My Angular script looks like this: 我的Angular脚本如下所示:

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



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

My test file looks like this: 我的测试文件如下所示:

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");
  });
});

This test fails saying $scope.test is undefined. 此测试失败,提示$ scope.test未定义。 I debugged in Chrome and saw that $scope has a bunch of properties on it, but none of them are test. 我在Chrome中进行了调试,发现$ scope上有很多属性,但是没有一个是经过测试的。 I've looked through several examples online, and they all look pretty similar to this. 我在网上浏览了几个示例,它们看起来都与此类似。 i'm not quite sure what i'm doing wrong here and i'm stuck.... 我不太确定自己在这里做错了什么,还是被困住了...。

edit I tried adding $controller to inject, but i'm still having the same problem. 编辑我试图添加$ controller注入,但我仍然有同样的问题。

You need to pass $controller service alongside with $rootScope : 您需要将$controller服务$rootScope一起传递:

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

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

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