茉莉花控制器测试中的角度范围

时间:2013-06-19 14:50:03

标签: unit-testing angularjs controller scope jasmine

试图了解茉莉花测试的工作原理。 我有一个模块和一个控制器:

var app = angular.module('planApp', []);

app.controller('PlanCtrl', function($scope, plansStorage){
var plans = $scope.plans = plansStorage.get();

$scope.formHidden = true;

$scope.togglePlanForm = function() {
    this.formHidden = !this.formHidden;
};

$scope.newPlan = {title: '', description: ''}   ;

$scope.$watch('plans', function() {
    plansStorage.put(plans);
}, true);

$scope.addPlan = function() {
    var newPlan = {
        title: $scope.newPlan.title.trim(),
        description: $scope.newPlan.description
    };

    if (!newPlan.title.length || !newPlan.description.length) {
        return;
    }

    plans.push({
        title: newPlan.title,
        description: newPlan.description
    });

    $scope.newPlan = {title: '', description: ''};
    $scope.formHidden = true;

};

});

plansStorage.get()是一个服务方法,它从localstorage获取一个json字符串并返回一个对象。

当我运行此测试时:

var storedPlans = [
  {
    title: 'Good plan',
    description: 'Do something right'
  },
  {
    title: 'Bad plan',
    description: 'Do something wrong'
  }
];

describe('plan controller', function () {
  var ctrl,
  scope,
  service;


  beforeEach(angular.mock.module('planApp'));
  beforeEach(angular.mock.inject(function($rootScope, $controller, plansStorage) {

    scope = $rootScope.$new();
    service = plansStorage;

    spyOn(plansStorage, 'get').andReturn(storedPlans);


    ctrl = $controller('PlanCtrl', {
      $scope: scope,
      plansStorage: service
    });

    spyOn(scope, 'addPlan')

  }));

  it('should get 2 stored plans', function(){
    expect(scope.plans).toBeUndefined;
    expect(service.get).toHaveBeenCalled();
    expect(scope.plans).toEqual([
  {
    title: 'Good plan',
    description: 'Do something right'
  },
  {
    title: 'Bad plan',
    description: 'Do something wrong'
  }
    ]);
  });

  it('should add a plan', function() {
    scope.newPlan = {title: 'new', description: 'plan'};
    expect(scope.newPlan).toEqual({title: 'new', description: 'plan'});
    scope.addPlan();

    expect(scope.addPlan).toHaveBeenCalled();

    expect(scope.plans.length).toEqual(3);
  });

});

第一次测试通过,但第二次测试失败。 scope.plans的长度预计为3,但它是2. scope.addPlan()调用后scope.plans没有改变。

如果我理解正确的话,addPlan方法中的$ scope与我在第二次测试中尝试测试的范围不同。

问题是为什么?我如何测试addPlan方法?

1 个答案:

答案 0 :(得分:1)

解决方案只是在间谍后添加andCallThrough()方法:

spyOn(scope, 'addPlan').andCallThrough()