Hello Everyone I am struggling at testing a $.on function and I am looking for any suggestions or help on this:
controller
$scope.$on("sampleFilesSelected", function(event, args) {
$scope.sampleFiles = args.newSampleFiles;
});
spec
describe('Testing a $.on', function() {
var $scope = null;
var ctrl = null;
beforeEach(module('test'));
it('should invoke myEvent when "myEvent" broadcasted', inject(function($rootScope, $controller) {
$scope = $rootScope.$new();
ctrl = $controller('MainCtrl', {
$scope: $scope
});
$scope.$broadcast('myEvent');
expect($scope.sampleFilesSelected).toBe(true);
}));
});
error
TypeError: Unable to get property 'newSampleFiles' of undefined or null reference
undefined
You should pass a value to your event, call a $digest before your assertion :
$scope.$broadcast('myEvent', { 'newSampleFiles' : true } );
$scope.$digest();
expect($scope.sampleFilesSelected).toBe(true);
this code ...
$scope.$broadcast('myEvent');
is not passing any args and so args.newSampleFiles throws an error because args is undefined
you need to pass args - how you do that I don't know
However, I would say ... unit testing is used for testing controller code not really for testing event handling. Your example is a bit of an edge case. I would be tempted to test the event handling use E2E testing and protractor.
I would refactor as follows ...
$scope.$on("sampleFilesSelected", function(event, args) {
$scope.sampleFiles = args.newSampleFiles;
});
would become ...
$scope.myFunction = function(event, args) {
$scope.sampleFiles = args.newSampleFiles;
}
$scope.$on("sampleFilesSelected", $scope.myFunction);
and i would unit test $scope.myFunction. And leave the testing of $scope.$on to E2E protractor testing.
Hope that helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With