【问题标题】:Jasmine Js - SpyOn Fakecall during the controller initializationJasmine Js - 控制器初始化期间的 SpyOn Fakecall
【发布时间】:2016-09-09 11:49:25
【问题描述】:

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

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

如何在控制器初始化期间停止调用实际的(控制器)fetchtemplate()?我的意图是在我的规范中模拟函数 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();
    });

我得到的结果是 - 首先是控制台项“控制器的功能”,然后是使用模拟功能执行规范。我希望模拟函数执行没有控制器的函数来执行

【问题讨论】:

  • 您也可以给我们控制器代码吗?我需要看看你是怎么调用那个 fetchtemplate 方法的
  • 当然,我也添加了控制器代码结构。 @山姆

标签: angularjs unit-testing jasmine karma-jasmine spyon


【解决方案1】:

因此,如果我理解正确,您正在调用一个函数,该函数正在执行您想要阻止以用于测试目的的事情。可能是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(...);
});


});

希望对你有帮助

【讨论】:

  • 嗨,山姆,感谢您的回复。我可以在不将函数放入服务的情况下解决问题吗?
  • 您可能可以通过覆盖角度基本行为或通过某种我从未发现的方式。正如你所说,你不能干预尚不存在的事情
猜你喜欢
  • 2013-04-22
  • 1970-01-01
  • 1970-01-01
  • 2016-12-31
  • 1970-01-01
  • 1970-01-01
  • 2017-01-20
  • 2016-01-27
  • 1970-01-01
相关资源
最近更新 更多