Jasmine Js - 控制器初始化期间的 SpyOn Fakecall

Jasmine Js - SpyOn Fakecall during the controller initialization

我看到了一组关于这个问题的重复问题,但无法解决问题。

我有一个控制器,在控制器初始化期间,首先调用 fetchtemplate(),然后调用我的模拟 fetchtemplate()。

如何停止在控制器初始化期间调用实际(控制器)fetchtemplate()?我的目的是在我的 spec.Please 中模拟函数 fetchtemplate() 看看我的规范 -

describe("...",function(){
   beforeEach(inject(function($controller,...) {
   scope        =   $rootScope.$new();

   this.init = function() {
                  $controller('ChangeControlCreateController', {
                    $scope: scope
                  });
                }
    }));
    describe('Function', function() {

        it("-- check for trueness",function(){

        this.init()     ; //Initialization of the controller
        spyOn(scope,'fetchtemplate').and.callFake(function() {
                  return 101;
                });
        var fakeResponse = scope.fetchtemplate();
        expect(scope.fetchtemplate).toHaveBeenCalled();
        expect(fakeResponse).toEqual(101);      
        });


    });
});

我曾尝试将 spyOn 放在 this.init() 之前,但出现错误,因为当时 fetchtemplate() 不存在 spyOn。

我的控制器代码结构如下-

angular.module('...', [...])

  .controller('ChangeControlCreateController', ["$scope"...,
    function ChangeControlCreateController($scope,...) {
        $scope.fetchtemplate = function() {
            console.log("controller's function");            
            ...
        };
        $scope.fetchtemplate();
    });

我得到的结果是 - 首先是控制台项 "controller's function",然后是使用模拟函数执行的规范。我希望模拟函数执行 而无需 控制器的函数执行

因此,如果我理解正确的话,您正在对一个函数进行一些调用,该函数正在执行您想阻止的测试目的。可能是 http 调用或类似的东西?

无论它采取什么正确的方式来处理类似的事情,通常是将该方法放入服务中,然后监视该服务方法。这是一个测试服务是否为 TemplateService 的示例:

describe("...",function(){

var $controller, scope, TemplateService, YourController;

beforeEach(inject(function(_$controller_, _TemplateService_, ...) {
  scope = $rootScope.$new();
  $controller = _$controller_;
  TemplateService = _TemplateService_;  
}

it("-- check for trueness",function(){

  spyOn(TemplateService,'fetchTemplate').and.returnValue('101');

YourController = $controller('YourController'); 
  expect(...);
});


});

希望对您有所帮助