I will be using Jasmine under Karma runner, some dependency injection code omitted for brevity.
Jasmine async tests
First, in order for any asynchronous unit test to work under Jasmine, just declare the test function to expect a single argument. This lets Jasmine engine now that your unit test is asynchronous. The argument will be a function your unit test is expected to call once it finishes.
1 | it('continues after 1 second', function (finished) { |
You can even shortcut calling finished
in most cases
1 | it('continues after 1 second', function (finished) { |
or if using with promise-returning code
1 | it('continues after a promise', function (finished) { |
testing $timeout
If you set actions to execute using $timeout
service, you can speed things
along by flushing
1 | var done = false; |
testing $httpBackend
Http requests sit in $httpBackend
until you flush them
1 | var done = false; |
testing $broadcast
Scopes listening to events, do NOT require any additional commands to propagate
1 | var done = false; |
testing promises
Any promise needs a digest cycle (scope $apply
call) to actually propagate along the chain
1 | var done = false; |
testing watchers
Any watchers on the scope needs a digest cycle (just like promise) to be updated
1 | var done = false; |
For a good AngularJS testing library that removes a lot of the boilerplate code, check out kensho/ng-describe