0

この質問の一連の重複を見ましたが、問題を解決できませんでした。

コントローラーがあり、コントローラーの初期化中に 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()、エラーが発生した前にspyOnを配置しようとしました。fetchtemplate()

私のコントローラーコード構造は次のようになります-

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

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

私が得ている結果は次のとおりです-最初にコンソールアイテム「コントローラーの機能」、次にスペックがモック機能で実行されています。コントローラーの関数を実行せずにモック関数を実行したい

4

1 に答える 1

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(...);
});


});

お役に立てば幸いです

于 2016-05-13T11:04:22.597 に答える