Javascript Jasmine spies函数调用

Javascript Jasmine spies函数调用,javascript,jasmine,Javascript,Jasmine,有以下代码: $scope.clickByPoint = function(marker, eventName, point) { var geocoder, location; $scope.options.info.point = point; $scope.options.info.show = true; $scope.searched = false; $scope.address = ""; geocoder = new googl

有以下代码:

  $scope.clickByPoint = function(marker, eventName, point) {
    var geocoder, location;
    $scope.options.info.point = point;
    $scope.options.info.show = true;
    $scope.searched = false;
    $scope.address = "";
    geocoder = new google.maps.Geocoder();
    location = {
      lat: parseFloat(point.latitude),
      lng: parseFloat(point.longitude)
    };
    geocoder.geocode({ location: location }, function(results, status) {
      $scope.searched = true;
      if (status === google.maps.GeocoderStatus.OK) {
        $scope.address = results[0].formatted_address;
      }
      return $scope.$digest();
    });
  };

请告诉我,我怎样才能“间谍”呼叫“geocoder.geocode”并执行假代码而不是它?提前谢谢

如果我理解正确的话,您希望对geocode函数进行模拟调用,只是为了检查您的控制器函数是否正确处理它,是吗

您应该使用Jasmine Spy的“调用和返回值”,这允许您在测试中调用函数,并硬编码希望该函数返回的结果。例如:

describe("A spy, when configured to fake a return value", function() {
  var foo, bar, fetchedBar;

  beforeEach(function() {
    foo = {
      setBar: function(value) {
        bar = value;
      },
      getBar: function() {
        return bar;
      }
    };

    spyOn(foo, "getBar").and.returnValue(745);

    foo.setBar(123);
    fetchedBar = foo.getBar();
  });

  it("tracks that the spy was called", function() {
    expect(foo.getBar).toHaveBeenCalled();
  });

  it("when called returns the requested value", function() {
      expect(fetchedBar).toEqual(745);
  });
});

您可以在此处查看茉莉花文档以了解更多信息:

是。我理解你的想法,但你的代码不起作用。你能检查并编辑吗?对不起,我是茉莉花的新手