监视在内部调用另一个api方法的方法

时间:2018-06-12 07:40:53

标签: javascript angularjs jasmine

我在控制器中有一个函数,它调用对象“映射”的方法。

$scope.createParameter = function (parameter) {
  var apiObj = {};
  mapping.createApiService(apiObj)
}

该对象结构如下,此方法'createApiService'调用apiService的'create'方法。

var mapping = {
  createApiService : apiService.create
}

我已将apiService注入我的Testsuite。并且如下添加了一个spyon。

spyOn(apiService, "create").and.callFake(function () {
  return {
    then: function (callback) {
      callback(createResponse);
      return {
        catch: function () {
        }
      }
    }
  }

但当我按照以下期望执行我的阻止时,它会给出一个错误“预期间谍创建被调用。

expect(apiService.create).toHaveBeenCalled();

有人可以帮我这个吗?

编辑:添加了测试代码

describe("Controller", function () {

    beforeEach(angular.mock.module("ui.router"));
    beforeEach(angular.mock.module("PpmApp"));

    var $controller, $scope, $state, $httpBackend, parameterDetails, apiService, constantsProvider;

    beforeEach(inject(function (_$controller_, _$rootScope_, _$state_, _$httpBackend_, _apiService_, _constantsProvider_) {
        $controller = _$controller_;
        $scope = _$rootScope_.$new();
        $state = _$state_;
        $scope.header = {};
        $state.current = {};
        $httpBackend = _$httpBackend_;
        apiService = _apiService_;
        constantsProvider = _constantsProvider_;
        $controller = $controller("Controller", { "$scope": $scope, "parameterDetails": parameterDetails });
    }));

   describe("create", function () {

        it("should succeed with valid Input", function () {
            var parameter = {
                ParameterType: 1,
                ParameterId: 2,
                LookupCurveStructures: [{
                    Name: "Parameter name",
                    XAxisName: "XAxisName",
                    YAxisName: "YAxisName",
                    XAxisDataType: 1,
                    YAxisDataType: 2
                }]
            };

            var createResponse = {
                Data: [],
                IsSuccess: true,
                Message: "Parameter added successfully"
            };

            spyOn(apiService, "create").and.callFake(function () {
            return {
              then: function (callback) {
                callback(createResponse);
                  return {
                    catch: function () {
                    }
                  }
                }
              }
            });
            $scope.createParameter(parameter);
            expect($scope.createPopupInfo.validationErrors.isError).toEqual(false);
            expect(apiService.create).toHaveBeenCalled();
            expect($scope.parameterDetails.Parameters).toEqual([]);
        });
    });
});

0 个答案:

没有答案