【问题标题】:Testing an http request where in success call another function with jasmine测试一个 http 请求,成功地用 jasmine 调用另一个函数
【发布时间】:2015-08-21 09:13:08
【问题描述】:

我有一个带有 http 请求的控制器。成功时它调用另一个函数,我不知道如何测试它。我是 Angular 新手。

var app = angular.module('myApp', ['']);
app.controller('MainController', ['$scope', '$http', function ($scope, $http) { 
$scope.source = '';
$scope.destination = '';
var selectedFiles = [];

$scope.deleteFiles = function(source) {
    if (source == $scope.source) {
        selectedFiles = selectedFilesSource;
    } else if (source == $scope.destination) {
        selectedFiles = selectedFilesDestination;
    }

    $http({
        method: 'POST',
        url: 'deleteFiles.php',
        data:
        {
            "sourcePath": source,
            "selectedFiles": selectedFiles
        }
    }).success(function(data) {
        if (source == $scope.source) {
            $scope.showFiles(source, 'source');
        } else if (source == $scope.destination) {
            $scope.showFiles(source, 'destination');
        }
    });
};

我的测试文件是这样的:

describe("Testing to MainController", function(){

beforeEach(module('myApp'));

var mainController, scope, httpBackend, http;

beforeEach(inject(function($controller, $rootScope, $httpBackend, $http) {
    scope = $rootScope;
    httpBackend = $httpBackend;
    http = $http;

    httpBackend.when('POST', 'deleteFiles.php', function(data){return{"sourcePath": "source", "selectedFiles": ''}})
       .respond(?????);
    mainController = $controller('MainController', {
        $scope: scope,
        $http: http
    });
}));



    it('should call showFiles if sourcepath is source', function() {
  scope.source = 'files/set1';
  scope.deleteFiles('files/set1');
  httpBackend.expectPOST('deleteFiles.php');
  httpBackend.flush();
  expect(scope.showFiles).toHaveBeenCalled();
});

});

错误消息:预期是间谍,但得到了函数。 我不在这里如何使用间谍,我不明白我应该在 httpBackend .respond 中有什么

【问题讨论】:

    标签: angularjs http jasmine


    【解决方案1】:

    当您的承诺成功解决后,就会调用$scope.showFiles(source, 'source'); 函数。因此,在 showFiles 上创建一个间谍。

    it('should call showFiles if sourcepath is source', function() {
      spyOn(scope, 'showFiles'); 
      scope.source = 'files/set1';
      scope.deleteFiles('files/set1');
      httpBackend.expectPOST('deleteFiles.php');
      httpBackend.flush();
      expect(scope.showFiles).toHaveBeenCalled();
    });
    

    【讨论】:

    • 我应该如何回应 httpBackend?
    • 应该有与实际响应中数据结构相同的模拟响应
    【解决方案2】:
    it('', function() {
      spyOn(scope, 'showFiles');
      scope.source = 'files/set1';
      scope.deleteImages('images/set1');
      // rest of your test ...
    });
    

    【讨论】:

      猜你喜欢
      • 2017-05-13
      • 2018-09-15
      • 1970-01-01
      • 1970-01-01
      • 2016-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多