2015-06-25 2 views
1

мне нужно пройти тест на обслуживание вызова с использованием jasmine.jsкод используется для тестирования в жасмин

код ниже моего angular.js вызова службы:

var myApp = angular.module('myApp',[]); 

    app.controller('Myctrl', function($scope, $http) { 
     $http.get("http://www.w3schools.com/angular/customers.php") 

     .success(function(response) {$scope.names = response.records;}); 

}); 

Как пройти тест блока используя jasmine.js? Я попытался это, но она не увенчалась успехом:

describe('Myctrl', function() { 

    var $httpBackend, scope, createController, authRequestHandler; 

    // Set up the module 
    beforeEach(module('myApp')); 

     alert("Hello there!"); 

    beforeEach(inject(function ($injector) { 
    // Set up the mock http service responses 
     alert("Hello there!"); 
    $httpBackend = $injector.get('$httpBackend'); 

    // backend definition common for all tests 
    alert("Hello there!"); 
    authRequestHandler = $httpBackend.whenGET('GET', 'http://www.w3schools.com/angular/customers.php') 
          .respond(true); 

    // Get hold of a scope (i.e. the root scope) 

    $rootScope = $injector.get('$rootScope'); 

    // The $controller service is used to create instances of controllers 
    var $controller = $injector.get('$controller'); 


    createController = function() { 

     return $controller('Myctrl', {'$scope' : scope}); 

    }; 

    }) 



); 
/* 
    afterEach(function() { 
    $httpBackend.verifyNoOutstandingExpectation(); 
    $httpBackend.verifyNoOutstandingRequest(); 
    }); 
*/ 


    it('should fetch authentication token', function() { 
     //create expectation 
    $httpBackend.expectGET('GET','http://www.w3schools.com/angular/customers.php') 
    var controller = createController() 
    $httpBackend.flush(); 
    expect(scope.names).toBeTruthy(true); 

    }); 


}); 
+1

Я отредактировал сообщение и опубликовал код, который я пробовал до сих пор – NAND

+0

Попробовал удалить все утверждения, повторяющие одно и то же. Надеюсь, теперь станет яснее –

ответ

1

Попробуйте это:

describe('Myctrl', function() { 
    var $httpBackend, $scope, authRequestHandler, createController, url; 
    $httpBackend = void 0; 
    $scope = void 0; 
    createController = void 0; 
    authRequestHandler = void 0; 
    url = void 0; 
    beforeEach(module('myApp')); 
    alert('Hello there!'); 
    beforeEach(inject(function($injector, $controller, $rootscope) { 
    var controllerService; 
    alert('Hello there!'); 
    $httpBackend = $injector.get('$httpBackend'); 
    alert('Hello there!'); 
    url = 'http://www.w3schools.com/angular/customers.php'; 
    $scope = $rootscope.$new(); 
    controllerService = $controller; 
    createController = function() { 
     return controllerService('Myctrl', { 
     '$scope': $scope 
     }); 
    }; 
    })); 

    /* 
    afterEach(function() { 
     $httpBackend.verifyNoOutstandingExpectation(); 
     $httpBackend.verifyNoOutstandingRequest(); 
    }); 
    */ 
    it('should fetch authentication token', function() { 
    $httpBackend.whenGET(url).respond(); 
    $httpBackend.expectGET(url).respond(); 
    $httpBackend.flush(); 
    createController(); 
    expect($scope.names).toBeTruthy(true); 
    }); 
}); 
+0

stll um получить сообщение об ошибке «неизвестный поставщик: $ controllerprovider» – NAND

0

Поясним все:

// group tests of the same component with 'describe' 
describe("MyCtrl", function() { 

    // where you put the reference of the controller 
    var myctrl; 
    // where you put the reference of the scope 
    var $scope; 
    // where you put the reference of httpBackend which simulate http request/response 
    var httpBackend; 

    // fake data 
    var data = { records: "Hello I am the server" }; 

    // function executed BEFORE each test ("it") 
    beforeEach(function() { 

     // load you module 
     module("myApp"); 

     // use the injector to get referencies 
     inject(function ($injector) { 
      // get $controller which allows you to generate a controller and to inject its dependencies 
      var $controller = $injector.get("$controller"); 
      // get $rootScope which allows you to generate a new scope empty 
      var $rootScope = $injector.get("$httpBackend"); 
      // get httpBackend 
      httpBackend = $injector.get("$httpBackend"); 

      // create a fake scope and store it in your reference 
      $scope = $rootScope.$new(); 
      // inject dependencies in your controller and get the reference 
      myctrl = $controller("MyCtrl", { 
       $scope: $scope, 
       $http: httpBackend 
      }); 

      // define what httpBackend do 
      httpBackend.whenGET("http://www.w3schools.com/angular/customers.php").respond(data); 
     }); 
    }); 

    // function executed AFTER each test ("it") 
    afterEach(function() { 
     // nothing here, you may even remove this "afterEach", it's just for the exemple 
    }); 

    // your first test 
    it("GET", function() { 
     // here your scope.names should be empty 
     expect($scope.names).toBeUndefined(); 

     // resole the request of httpBackend 
     httpBackend.flush(); 

     // now your scope.names should be the fake data.records 
     expect($scope.names).toEqual(data.records); 
    }); 
}); 

Я не проверял, он может содержать некоторые ошибки, но метод здесь. Это зависит от вас сейчас;)

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