javascript - 无法对通过 Controller 发生的 http 调用进行单元测试

标签 javascript angularjs unit-testing karma-jasmine

我正在尝试编写代码来测试在我的 Controller 中完成的服务调用。我正在尝试对 Controller 中的特定功能进行单元测试,该功能正在执行服务调用并带来数据。目前我正在尝试使用本地 json,但它实际上会进行服务调用。

我知道首先我必须创建一个 spy 对象,但我收到了错误,我的目标是成功地对 Controller 中发生的 http 调用进行单元测试。

我是单元测试的新手。粘贴我的代码,请求你帮助我,从现在开始很多天一直在努力。我也经历了很多解决方案,它们是如此不同,让人感到困惑。非常感谢你的帮助

服务代码:

    //xlpApp is the module name
    xlpApp.factory('xlpServices', ['$rootScope', '$http', function($rootScope, 
    $http) {
    var xlpServices = {};
    xlpServices.getProgramData = function(){
          return $http.get(scripts/services/data/unitTesting.json'); 
     };

unitTesting.json 代码:

    {
    "name":"unit testing"
    }

Controller 代码:

$scope.events = {

    programData: function(){
            xlpServices.getProgramData().then(function(response) {
                if (response && response.data) {
                    $scope.testVariable= response.data.name;
                }
            });
        },
    selectSortingType : function(type) {
            $scope.selectedSorting = type;
            selectedFilter.sortingBy = $scope.selectedSorting;
        }   

}
$scope.events.programData();  

单元测试代码:

  describe('myProgramGpmCtrl', function() {
  beforeEach(module('xlp'));

  var $controller;

  beforeEach(inject(function(_$controller_){
    $controller = _$controller_;
  }));

describe('service call test', function() {
    var xlpServices , myService , $q;
    var $scope = {};

     beforeEach(inject(function(xlpServices,_$q_){
       xlpServices = xlpServices;
       $q = _$q_;
       var controller = $controller('myProgramGpmCtrl', { $scope: $scope });
       myService = jasmine.createSpyObj('xlpServices',['getProgramData']);
    }));

    it('Service call test ', function() {
      expect(myService.getProgramData).toHaveBeenCalled();
    }); 
});

});

错误:

      Expected spy xlpServices.getProgramData to have been called.

最佳答案

尝试类似的东西,

describe('service call test', function() {
    var xlpServicesMock , myService , $q;
    var $scope = {};

     beforeEach(inject(function(xlpServices,_$q_){
       xlpServicesMock = xlpServices;
       $q = _$q_;
       spyOn(xlpServicesMock ,'getProgramData').and.callFake(function() {
        // we can return promise instead this custom object  
        return {
            then: (callback, errorCallback) => {
                callback('data to be passed to then callback');
                /* `callback` function should be invoked when you wanted to test the service for success response with status code 200.
                   `errorCallback` function should be invoked with 500 status code when you wanted to test the api failure
                Ex: callback({status: 200, data: <your data here>);
                    errorCallback({status: 500, data: <your error data>})
                You can prepare the response to be passed as you wanted.

                 */

            }
        };
       });

       var controller = $controller('myProgramGpmCtrl', { $scope: $scope, xlpServices: xlpServicesMock  });

    }));

    it('Service call test ', function() {
      $scope.events.programData();
      expect(myService.getProgramData).toHaveBeenCalled();
    }); 
});

网上有很好的资源。 检查herehere

关于javascript - 无法对通过 Controller 发生的 http 调用进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47893788/

相关文章:

php - 如果旋转正在移动则停止视频

javascript - jQuery在点击时改变多个元素的颜色

c# - 单元测试异常处理

angularjs - Protractor 是 Angular 的新场景运行器吗?

java - TestNG中@DataProvider和@Parameters的区别

javascript - Jasmine : Add source method for test execution

javascript - 是否可以在 Konva.js 中测量当前的 FPS?

javascript - 在单选按钮上显示/隐藏 div 并更改表单操作

node.js - 使用 Node.js (express)、Angular 和 MongoDB 的 PUT 请求出现问题

javascript - 将函数参数传递给 $scope.$apply?