Spy on a service method call using jasmine Spies

后端 未结 1 1011
鱼传尺愫
鱼传尺愫 2020-12-14 03:14

I have the following controller ViewMeetingCtrl.js

(function () {
    \'use strict\';
    angular.module(\'MyApp\').controller(\'ViewMeeting         


        
相关标签:
1条回答
  • 2020-12-14 03:38
    describe('ViewMeetingCtrl', function () {
    
        var scope, meetingService;
    
        beforeEach(angular.mock.module('MyApp'));
    
        beforeEach(inject(function ($rootScope, $controller, _meetingService_) {
            scope = $rootScope.$new();
            meetingService = _meetingService_;
            $controller('ViewMeetingCtrl', {
                $scope: scope,
                meeting : {}
            }); 
        }));
    
        it('should send cancel notices whan cancelMeeting is called', function() {
            var fakeHttpPromise = {
                success: function() {}
            };
            spyOn(meetingService, 'sendCancelNotices').andReturn(fakeHttpPromise);
    
            scope.cancelMeeting('foo', 'bar');
    
            expect(meetingService.sendCancelNotices).toHaveBeenCalledWith('bar', 'foo');
        });
    
    });
    

    I would encourage you to stop relying of HTTP promises being returned from services. Instead, just consider the service returns a promise. Those are easier to mock, and won't force you to rewrite your controller code when you don't return HTTP promises anymore.

    In your controller:

        function cancelMeeting(meetingId, companyId) {
            meetingService.sendCancelNotices(companyId, meetingId)
                .then(function () {
                    $state.go('company.view');
                });
        } 
    

    In your test:

            var fakePromise = $q.when();
            spyOn(meetingService, 'sendCancelNotices')and.returnValue(fakePromise);
    
            scope.cancelMeeting('foo', 'bar');
            expect(meetingService.sendCancelNotices).toHaveBeenCalledWith('bar', 'foo');
    
    0 讨论(0)
提交回复
热议问题