如何使用茉莉花模拟对JS异步进行单元测试

时间:2019-03-03 01:04:56

标签: javascript angularjs unit-testing promise jasmine

我对JS还是一个新手,在使用茉莉花模拟测试异步方法时遇到了一些问题。

这是我要测试的课程:

 test.factory('service', ['$http', '$q', function($http, $q) {
     var _func = function(varB, successCallback, errorCallback) {

         //Sanity check on input
         if (isNaN(varB)) {
             errorCallback('varB has to be a number');
             return;
         }

         if (parseInt(varB) < 0) {
             errorCallback('varB count has to be positive');
             return;
         }

         $http.get('http://www.test.com').then(function(response) {
             var data = angular.copy(response.data);
             if (successCallback) {
                 successCallback(data);
             }
         }, function(errorResponse) {
             if (errorCallback) {
                 errorCallback(errorResponse.data);
             }
         });
     };

     return {
         func: function(varB) {
             return $q(function(resolve, reject) {
                 _func(varB, resolve, reject);
             });
         }
     };
 }]);

其中一项测试:

 beforeEach(inject(function($injector) {
     service = $injector.get(
         'service');
     $httpBackend = $injector.get('$httpBackend');
 }));

 it('should use the rejection handler if varB is in invalid format',
     function() {
         var successHandler = jasmine.createSpy('success');
         var failHandler = jasmine.createSpy('fail');
         service.func('abc').then(successHandler, failHandler);
         expect(successHandler).not.toHaveBeenCalled();
         expect(failHandler).toHaveBeenCalledWith('varB has to be a number');
     }
 );

测试中的行:     expect(failHandler).toHaveBeenCalledWith('varB has to be a number');出于某种原因永远不会执行。我什至尝试将调试语句放入服务类中,以查看是否已到达方法以及是否已到达方法。但是该模拟无法检测到使用给定参数调用了回调。

很高兴获得一些见解!谢谢!

1 个答案:

答案 0 :(得分:0)

好,我找到了解决方法。

提示here

因此,要添加一个rootScope注入。在那之后工作了! :)

beforeEach(inject(function($injector) {
     service = $injector.get(
         'service');
     $httpBackend = $injector.get('$httpBackend');
     $rootScope = $injector.get('$rootScope');
 }));

 it('should use the rejection handler if varB is in invalid format',
     function() {
         var successHandler = jasmine.createSpy('success');
         var failHandler = jasmine.createSpy('fail');
         service.func('abc').then(successHandler, failHandler);
         $rootScope.$digest();
         expect(successHandler).not.toHaveBeenCalled();
         expect(failHandler).toHaveBeenCalledWith('varB has to be a number');
     }
 );