2

Я использую угловые js, и у меня есть controller.js, для которого я хочу написать тестовый случай жасмина. Я могу вызвать функцию контроллера в своей тестовой папке. В моем контроллере есть локальная функция, вызываемая методом в области (для которой я пишу тестовый пример), который вызывает метод службы с помощью ajax-запроса.

Я не могу издеваться этот запрос HTTP POST, в моем тесте с помощью $ httpbackend

(function() { 
    'use strict'; 
    angular 
     .module('coApp') 
     .controller('NewController', [ 
     '$http', 
     '$q', 
     '$log', 
     '$modal', 
     '$scope', 
     'AgentDataLoader', 
     '$timeout', 
     NewController]); 

    function NewController ($http, $q, $log, $modal, $scope, $state, $rootScope, $filter, AgentDataLoader, $timeout) { 

     //Some variables declarations 

     //some methods 
     function myMethod($filter, a, b) { 
      console.log("inside myMethod"); 
      if (angular.isDefined(a) && angular.isDefined(b)) { 
       console.log("inside if "); 
       console.log("a:: "+a); 
       console.log("b:: "+b); 

       dataLoader.callPOST(a, b) 
        .then(function (data) { 
        console.log("Data from service :: "+JSON.stringify(data)); 
        /**calling some directive and methods 
         I am unable to execute this since I am unable to mock http Post of above mentioned dataLoader 
        **/ 

       console.log("after http request"); 
      } else { 
       //some other logic 
      } 
     } 



     $scope.methodToBeTested= function (randomData) { 
      console.log("selectedSystems called ****** "); 
      //some logic 
myMethod($filter, $scope.a, $scope.b); 

     }; 
})(); 

Мой жасмин тестовый набор

describe('NewController',function(){ 
    var ctrl, scope, $httpBackend, $compile, parameters; 
    beforeAll(function (done) { 

    });  


    beforeEach(function() { 
     module('MYmODULE'); 
     module('myServiceModule'); 
    }); 

    beforeEach(inject(function ($controller, _$httpBackend_, $rootScope, _$compile_) { 
     scope=$rootScope.$new(); 
     $compile = _$compile_; 
     $httpBackend = _$httpBackend_; 
     ctrl=$controller('NewController',{$scope: scope}); 
     // Start listening to xhr requests 

     //This data i want to send as a success of httpBackEnd Post 
     success.data = JsonData; 

     console.log('Setting request in $httpBackend'); 

     //Not working 
     $httpBackend.whenPOST('/abc/efg').success(function(method, url, data) { 
      console.log("Getting sample data from httpBackend :: "+url); 
      return [200, success.data, {}]; 
     }); 

     //Not working 
     $httpBackend.whenPOST('abc/efg').respond(function(method, url, data, headers){ 
      console.log('Received these data:', method, url, data, headers); 
      phones.push(angular.fromJson(data)); 
      return [200, {}, {}]; 
     }); 

     $httpBackend.flush();  
    })); 

    it("Testing myMethodToBeTested of the page", function(){ 
     scope.randomData=someRandomData; 
     expect(scope.methodToBeTested(scope.randomData)); 

     //Tried this also not working 
     $httpBackend.expectPOST('/abc/efg').respond(success.data); 

     afterEach(function() { 
    }); 
}); 
+0

изменения вам код состояния 201, как это после вызова –

ответ

0

Для вас TestCase костюм вы должны издеваться данные ответа , Я думаю, что в приведенном выше коде я не вижу, чтобы переменная успеха была запитана где угодно. Так что если вы хотите, чтобы получить ожидаемый ответ, вы должны назначить ожидаемый объект в переменной Success (на основе выше публикуемую кода), как Ex:

var Success = {data:{SomeKey:"value"}} 

Теперь вы должны передать эту переменную в POST/GET запрос , Как

$httpBackend.expectPOST('/abc/efg').respond(Success.data); 

Надеется, что это помогает :)

 Смежные вопросы

  • Нет связанных вопросов^_^