在jasmine

时间:2015-06-10 12:32:51

标签: angularjs unit-testing jasmine karma-runner karma-jasmine

这是我的控制器中的一个功能



function sendMeetingInvitation(companyId, meetingId) {

  meetingService.sendInvitations(companyId, meetingId)
    .success(function() {
      $state.go('company.meeting.view', {}, {
        reload: true
      });
    })
    .error(function() {
      //more code for error handling
    });

}




以下是我在调用sendMeetingInvitation()时测试的测试用例,是否应该调用success() <{1}}服务调用的meetingService.sendInvitations块/ p>

&#13;
&#13;
describe('EditMeetingCtrl.sendMeetingInvitation()', function() {
  var $rootScope, scope, $controller, $q, companyService, meetingService;



  var mockedHttpPromise = {
    success: function() {}
  };

  beforeEach(angular.mock.module('MyApp'));


  beforeEach(angular.mock.inject(function(_$httpBackend_, _companyService_, _meetingService_) {
    $httpBackend = _$httpBackend_;
    companyService = _companyService_;
    meetingService = _meetingService_;
  }));

  beforeEach(inject(function($rootScope, $controller, _meetingService_) {
    scope = $rootScope.$new();
    createController = function() {
      return $controller('EditMeetingCtrl', {
        $scope: scope,
        meeting: {},
        meetingService: _meetingService_
      });
    };
    var controller = new createController();
  }));

  it("should should send invitations", function() {
    spyOn(meetingService, 'sendInvitations').and.returnValue(mockedHttpPromise);
    scope.sendMeetingInvitations(123456, 123456);
    expect(meetingService.sendInvitations).toHaveBeenCalledWith(123456, 123456);
  });


});
&#13;
&#13;
&#13;

我收到这个错误并没有用。

PhantomJS 1.9.8 (Windows 8) In EditMeetingCtrl EditMeetingCtrl.sendMeetingInvitation() should should send invitations FAILED
TypeError: 'undefined' is not an object (near '...})...')

我在这做错了什么?我尝试了mockedHttpPromise跟随。但结果相同

&#13;
&#13;
var mockedHttpPromise = {
  success: function() {},
  error: function() {}
};
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

sendInvitations函数希望返回一个promise,因此,您需要做的是创建一个defer并将其返回,如下所示:

- 首先你需要注入$ q:$q = $injector.get('$q');

创建延迟:deferred = $q.defer();

你的函数mockedHttpPromise,应该如下:

function mockedHttpPromise() {
    deferred = $q.defer();
    return deferred.promise;
}

在测试中:

  it("should should send invitations", function() {
    spyOn(meetingService, 'sendInvitations').and.returnValue(mockedHttpPromise);
    scope.sendMeetingInvitations(123456, 123456);
    deferred.resolve({});
    scope.$apply();
    expect(meetingService.sendInvitations).toHaveBeenCalledWith(123456, 123456);
  });

要测试错误阻止,请将deferred.resolve更改为deferred.reject