I have problem to write a unit test for my controller which test orderBy in the table with elements.
I have advert.html:
<body ng-app="motoAdsApp" ng-controller="AdvertsController">
<form>
<label>Sort by</label>
<select ng-model="sortByCol" ng-options="s.name for s in sortByCols">
<option value=""></option>
</select>
</form>
<br/>
<table border="1">
<tr ng-repeat="advert in adverts| orderBy:sortByCol.key">
<td>
<span>{{advert.countryName}}, {{advert.regionName}}</span>
</td>
<td>{{advert.brandName}}</td>
<td>{{advert.modelName}}</td>
<td>{{advert.year}}</td>
<td>{{advert.price}}</td>
</tr>
</table>
</body>
controllers.js:
var motoAdsApp = angular.module('motoAdsApp', []);
motoAdsApp.controller('AdvertsController', ['$scope', function($scope) {
$scope.sortByCols = [{
"key": "year",
"name": "Year"
}, {
"key": "price",
"name": "Price"
}];
$scope.adverts = [];
var allAdverts = ADVERTS_RESPONSE;
$scope.filter = {
brandName: null,
modelName: null,
country: null,
region: null,
yearFrom: null,
yearTo: null
};
$scope.$watch('filter', filterAdverts, true);
function filterAdverts() {
$scope.adverts = [];
angular.forEach(allAdverts, function(row) {
if (!$scope.filter.country) {
$scope.filter.region = null;
}
if ($scope.filter.brandName && $scope.filter.brandName !== row.brandName) {
return;
}
// ...
$scope.adverts.push(row);
});
}
}
]);
My unit test controllersSpec.js:
describe('MotoAds controllers', function() {
beforeEach(function() {
this.addMatchers({
toEqualData: function(expected) {
return angular.equals(this.actual, expected);
}
});
});
beforeEach(module('motoAdsApp'));
describe('AdvertsController', function() {
var scope, ctrl, $httpBackend;
beforeEach(inject(function(_$httpBackend_, $rootScope, $controller) {
$httpBackend = _$httpBackend_;
$httpBackend.expectGET('data/adverts.json').respond(ADVERTS_RESPONSE);
scope = $rootScope.$new();
ctrl = $controller('AdvertsController', {$scope: scope});
}));
it('should sort by year', function() {
$httpBackend.flush();
scope.$apply(function() {
scope.sortByCol = { key: "year"};
});
var prevYear = 0;
for (var i = 0; i < scope.adverts.length; i++) {
var advert = scope.adverts[i];
expect(advert.year).toBeGreaterThan(prevYear);
prevYear = advert.year;
}
});
});
});
After run my test I have this:
Chrome 30.0.1599 (Windows Vista) MotoAds controllers AdvertsController should so
rt by year FAILED
Expected 2010 to be greater than 2011.
Error: Expected 2010 to be greater than 2011.
at null.<anonymous> (D:/projects/motoads/test/unit/controllers
Spec.js:147:29)
Expected 2009 to be greater than 2012.
Error: Expected 2009 to be greater than 2012.
I think that the elements (adverts) are not sorted. Why? What I should do?