I am writing a unit test for a function within my controller.
The function uses the $filter to format the date in 'yyyy-MM-dd' format.
However my karma script fails to run after the line on which the filter is used.
Here's the function:
$scope.myFunction = function (someDate) {
var dateTo = new Date(someDate);
var myDate = $scope.myDate;
// Code fails after line below on unit test /////
var searchdate = (filter('date')(myDate, 'yyyy-MM-dd'));
searchdate = serviceConvertISODate.convertDate(searchdate);
}
In the example above, var myDate = 1405967947000 (epoc format)
Unit test:
describe('Validating functions within Controller', function () {
var scope, ctrl, filter, localServiceConvertISODate;
beforeEach(inject(function($controller, $rootScope, $filter, serviceConvertISODate) {
scope = $rootScope.$new(),
ctrl = $controller('MyController', {
$scope: scope,
filter : $filter,
serviceConvertISODate : localServiceConvertISODate
});
}));
it('should test my function', function() {
var dateTo = new Date("22 Sep 2014");
console.log("********* dateTo = " + dateTo );
var myDate = $scope.myDate;
console.log("********* myDate = " + myDate );
var searchdate = (filter('date')(myDate, 'yyyy-MM-dd'));
console.log("searchdate after filter = " + searchdate);
searchdate = localServiceConvertISODate.convertDate(searchdate);
});
});
I can see through my logs:
dateTo is returning the correct new date
myDate is returning the correct myDate
However, applying the next line (filter), causes the test to break and no error is provided.
Check your code. You're passing the AngularJS $filter
to your controller as filter
for some reason (why?), which could work if your controller requests that injection, but then you try to use filter
variable in your test code, where it's value is undefined. Set the value in your beforeEach()
if you want to use it later:
filter = $filter;
Also, I'm not sure whether you're just debugging or if the provided code shows what you're trying to do. If the latter, note that the unit-test should test your unit from "outside". So it should really be calling your $scope.myFunction
with some data and testing if the result fits your expectations. You don't copy the insides of your function to your tests.