Angular: List name test $http
http://angularjs.org/
HTML
<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
<script src="https://raw.github.com/pivotal/jasmine/master/lib/jasmine-core/jasmine.js"></script>
<script src="https://raw.github.com/pivotal/jasmine/master/lib/jasmine-core/jasmine-html.js"></script>
<script src="http://code.angularjs.org/1.0.1/angular-mocks-1.0.1.js"></script>
<link rel="stylesheet" href="http://tryjasmine.com/js/vendor/jasmine-1.1.0/jasmine.css">
<link rel='stylesheet' href='http://tryjasmine.com/js/vendor/jasmine-1.1.0/jasmine.css' />
<script type='text/javascript' src='https://raw.github.com/pivotal/jasmine/master/lib/jasmine-core/jasmine.js'></script>
<script type='text/javascript' src='https://raw.github.com/pivotal/jasmine/master/lib/jasmine-core/jasmine-html.js'></script>
<script type='text/javascript' src='http://code.angularjs.org/angular-1.0.1.js'></script>
<script type='text/javascript' src='http://code.angularjs.org/1.0.1/angular-mocks-1.0.1.js'></script>
<body ng-app='myApp'>
<div ng-controller='listController'>
<p ng-repeat='pat in patient'>{{pat.name}}</p>
</div>
</body>
JavaScript
describe('Testing a controller', function() {
// chargement du module controllers
beforeEach(module("myApp"));
var ctrl, scope, httpMock;
// injection du service $controller, du $rootScope, du $httpBackend
beforeEach(inject(function($controller, $rootScope, $httpBackend) {
httpMock = $httpBackend;
// création d'un nouveau scope
scope = $rootScope.$new();
// simulation d'un requete GET sur la resource data/patients.json
httpMock.when('GET', 'data/patients.json').respond([{name: 'name1'}, {'name': 'name2'}]);
//httpMock.expectGET('data/patients.json').respond([{name: 'name1'}, {'name': 'name2'}]);
// création du controller avec le nouveau scope, le mock de $http
ctrl = $controller("listController", {
$scope: scope
});
httpMock.flush();
}));
// test de récupération des données patients
it('test load patients', function() {
// la chaine de caractère "name1" est elle bien dans le premier objet du tableau ?
expect(scope.patients[0].name).toMatch("name1");
});
// test de la méthode addPatient()
it('test add patient', function() {
scope.patient = "test";
scope.addPatient();
// la chaine de caractère "test" est elle bien dans le dernier objet du tableau ?
expect(scope.patients[scope.patients.length-1].name).toMatch("test");
});
afterEach(function() {
httpMock.verifyNoOutstandingExpectation();
httpMock.verifyNoOutstandingRequest();
});
});
angular.module('myApp',[]).
controller("listController", ["$scope", "$http", "$log", function ($scope, $http, $log) {
$http.get("data/patients.json").
success(
function (data, status, headers, config) {
$scope.patients = data;
}).
error(function (data, status, headers, config) {
$log.error("error getting movies : " + data);
...