2016-11-30 7 views
0

を使用してこの機能をテストする方法については、これはコントローラ内の関数である:私は希望

describe('Controller: MyCtrl', function() { 
    'use strict'; 

    var MyCtrl; 
    var rootScope; 
    var scope; 
    var httpMock; 

    beforeEach(function() { 
    module('MyModule'); 

    inject(function($controller, $rootScope, $httpBackend) { 
     rootScope = $rootScope; 
     scope = $rootScope.$new(); 
     httpMock = $httpBackend; 
     MyCtrl = $controller('MyCtrl as vm', { 
     $rootScope: rootScope, 
     $scope: scope, 
     $http: httpMock, 
     }); 
    }); 
    }); 

    describe('vm.getData()', function() { 
    it('returns the required data', function() { 
     httpMock.when('GET', '/get-data?query=test-val').respond(200, {data: 'test-data'}); 
     httpMock.flush(); 
     expect(scope.vm.getData('test-val')).toEqual('test-data'); 
    }); 
    }); 
}); 

var vm = this; 
vm.getData = getData; 

function getData(val) { 
    return $http.get('/get-data', { 
    params: { 
     query: val 
    } 
    }).then(function(response) { 
    return response.data; 
    }); 
} 

、これが私の(ストリップダウン)テストファイルでありますgetData()を呼び出すと正しいデータが返されたかどうかをテストします。

現在、私はエラー$http.get is not a functionを得ています。私の関数にブレークポイントを設定すると、httpが$ httpBackendでスタブされていることがわかります。

私は把握していない何か基本的なものがあると思います。どんな指針も高く評価されます。

答えて

0

あなたは、コントローラを作成する必要はありません。バックエンドを模擬するために

$http: $httpBackend 

。 $ httpBackendはすでにリクエスト自体をモックするでしょう。また、テストとアサーションが間違った順序で行われ

httpMock.when('GET', '/get-data?query=test-val').respond(200, {data: 'test-data'}); 
MyCtrl.getData('test-val').then(function(_result_){ //perform the request 
    result = _result_;        //save the result of the promise 
}); 
httpMock.flush();         //execute the request 
expect(result).toBe('test-data');     //assert that the result is as expected 
+0

素晴らしいです - あなたは非常に多くのjlastに感謝:) – Jay

+0

ただ、完全を期すために、ここで必要なのカップルとそのブロックが償いです: ' ( 'GET'、 '/get-data?query=test-val').respond(200、{data}、{get_data_query}、{get_data} : 'test-data'}); MyCtrl.getData( 'test-val')(function(_result _){ result = _result_; }); httpMock.flush(); expect(result).toEqual({data: 'テストデータ'}); }}); ' – Jay

関連する問題