0

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

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;

};

});

planStorage.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.plans 在 scope.addPlan() 调用后没有改变。

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

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

4

1 回答 1

1

解决方案只是andCallThrough()在 spy 之后添加方法:

spyOn(scope, 'addPlan').andCallThrough()
于 2013-06-19T15:32:47.810 回答