AngularJS控制器测试范围未定义

时间:2015-05-08 01:01:18

标签: javascript angularjs jasmine karma-runner browserify

我在测试AngularJS控制器时遇到问题。控制器使用a 服务以获取一些数据并将其放在$ scope。

// src/controllers/posts.js
module.exports = ['$scope', 'posts', function($scope, posts) {
  posts.refresh(function(err, data) {
    $scope.posts = data;
  });
}]

// src/services/posts.js
module.exports = ['$http', function($http) {
  this.refresh = function(callback) {
    $http.get('/posts')
      .success(function(data, status, headers, config) {
        callback(null, data);
      })
      .error(function(data, status, headers, config) {
      });
  };
}]

// src/app.js
var angular = require('angular');
var PostsController = require('./controllers/posts');
var PostsService = require('./services/posts');

var simpleApp = angular.module('simple-app', []);

simpleApp.controller('PostsController', PostsController);

simpleApp.service('posts', PostsService);

当我在浏览器中运行它时,这一切都有效。我对与Karma和Jasmine合作的服务进行了功能测试。我在控制器测试中遇到的问题是结果是$ scope未定义。

以下是测试:

// test/controllers/posts.test.js
var fixtures = require('../fixtures/posts');

describe('PostsController', function() {
  var PostsController, scope;

  beforeEach(angular.mock.module('simple-app'));

  beforeEach(angular.mock.inject(function($rootScope, $controller, _posts_) {
    scope = $rootScope.$new();

    PostsController = function() {
      return $controller('PostsController', {
        $scope: scope,
        posts: _posts_
      });
    };
  }));

  it('should set the posts on the scope', function() {
    debugger; // shows me that the scope's posts property isn't set
    var controller = PostsController();
    expect(scope.posts).toEqual(fixtures);
  });
});

从文档中,$ controller返回指定控制器的新实例。所以,当我调用PostsController()时,它应该返回注入了依赖项的新实例吗?实例化实例时,它应该运行控制器函数,操纵测试中注入的范围。有什么我想念的吗?

编辑:我已将$ httpBackend添加到测试中,但现在测试显示httpBackend未定义。这是代码(只有改变的函数):

beforeEach(angular.mock.inject(
  function($rootScope, $controller, _posts_, $httpBackend) {
    scope = $rootScope.$new();

    PostsController = function() {
      return $controller('PostsController', {
        $scope: scope,
        posts: _posts_
      });

    httpBackend = $httpBackend;
  };
}));

it('should set the posts on the scope', function() {
  debugger; // checking httpBackend here says httpBackend is undefined
  httpBackend.whenGET('/posts').respond(fixtures);

  var controller = PostsController();
  expect(scope.posts).toEqual(fixtures);
});

0 个答案:

没有答案