To write a Jasmine unit test for $q.all, you need to mock the promises and test the behavior when all promises are resolved or when any of them is rejected. Here's a step-by-step example of how to do it:

Suppose you have a service that has a method which uses $q.all to handle multiple promises:

javascript
// Sample service with $q.all angular.module('myApp').service('MyService', function($q, ApiService) { this.getData = function() { var promise1 = ApiService.fetchData1(); var promise2 = ApiService.fetchData2(); return $q.all([promise1, promise2]); }; });

Now, let's write a Jasmine unit test for this service method:

javascript
describe('MyService', function() { var $q, $rootScope, ApiService, MyService; beforeEach(module('myApp')); beforeEach(inject(function(_$q_, _$rootScope_, _ApiService_, _MyService_) { $q = _$q_; $rootScope = _$rootScope_; ApiService = _ApiService_; MyService = _MyService_; })); it('should resolve the promises', function(done) { // Mock the ApiService fetch methods spyOn(ApiService, 'fetchData1').and.returnValue($q.resolve('Data 1')); spyOn(ApiService, 'fetchData2').and.returnValue($q.resolve('Data 2')); // Call the method being tested var promise = MyService.getData(); // Resolve the promises $rootScope.$apply(); promise.then(function(results) { // Expect the promises to be resolved with the correct data expect(results[0]).toBe('Data 1'); expect(results[1]).toBe('Data 2'); done(); }); }); it('should reject if any promise is rejected', function(done) { // Mock the ApiService fetch methods spyOn(ApiService, 'fetchData1').and.returnValue($q.resolve('Data 1')); spyOn(ApiService, 'fetchData2').and.returnValue($q.reject('Error fetching Data 2')); // Call the method being tested var promise = MyService.getData(); // Resolve the promises $rootScope.$apply(); promise.catch(function(error) { // Expect the promise to be rejected with the correct error message expect(error).toBe('Error fetching Data 2'); done(); }); }); });

In the first test, we mock the ApiService fetch methods to return resolved promises with specific data. We then call MyService.getData() and use $rootScope.$apply() to resolve the promises. Finally, we use then() to handle the resolved value and check if the expected data is returned.

In the second test, we mock one of the ApiService fetch methods to return a rejected promise with an error message. We use the same approach to call MyService.getData() and resolve the promises. Then, we use catch() to handle the rejected value and verify if the expected error message is returned.

Remember to use $rootScope.$apply() after mocking the promises to resolve them in the AngularJS context. Also, make sure to handle the promises properly in your application code, such as using catch() to handle errors when using $q.all.

Have questions or queries?
Get in Touch