Tag Archives: unit test

Unit testing $scope.$on(‘$viewContentLoaded’) on an Angularjs Controller

TL;DR = call


in your unit test. This will call your

$scope.$on('$viewContentLoaded', function () {}); 

method in your controller

If you have a Controller that has a method that is not fired until the view is loaded you will have a method similar to the following:

    $scope.$on('$viewContentLoaded', function () {

The test case needs to wire in the $scope into your test like below

describe('when the campaign controller is initialized', function () {

 beforeEach( function() {
 } );

 it('should call the getAllCampaignTypes service call', function () {
     expect(mockedSomeService.callMethods).toHaveBeenCalledWith( ... );

The Most important thing is the call to $scope.$broadcast(‘$viewContentLoaded’);

Angularjs-mock testing $http by mocking using httpBackend and flush() not working.


I was writing a unit test for my angularjs app and I ran into the following problem.

I was setting up the test correctly to inject in the $httpBackend to mock out the http calls, but the when I called called the service and then called $httpBackend.flush() it would return an error:

httpBackend no pending request to flush

Which is not what I was expecting.

Other background

When I commented out the $httpBackend.whenGET
The following 2 methods in the afterEach function would not throw an error either.


This would pass the test even though the expectations were never triggered.

Here is an example of the code I was testing with.

Continue reading

Unit testing angularjs with $http

Angularjs unit testing with $http.

How it all hangs together

When calling external servers to get or push data you can use the $http from angular.  $http has a set of methods like Get, Post and Put like you would expect.

$http callback methods.

It treats the call much like a ajax call where it has a .success method and a .error method which it returns to depending on if the call success or failure.

Scoping of parameters and .success() and .errror()

You can interact with the $scope or $rootScope to set or change data.  The scoping of the .success() and .error() means you cannot use a method level parameter and expect the value to be assigned before the the method ends.  It can go out of scope before it is guaranteed to be set.

Continue reading