I'm trying to unit test a service that uses a repository which in turn returns a promise to the consumer.
I'm having trouble testing the promise, or I should say I don't know how test the promise.
Any help would be appreciated!
1 Answer
This is the test with $httpBackend and for mocking the service.
var describe = window.describe,
beforeEach = window.beforeEach,
afterEach = window.afterEach,
it = window.it,
expect = window.expect,
inject = window.inject,
module = window.module,
angular = window.angular,
serviceURL = '/' + Techsson.Core.Global.Language + '/api/sessionlimit/getdata',
$scope,
sessionLimitServiceResponse;
describe('Jasmine - SessionLimitService', function () {
beforeEach(module('sessionlimit.module'));
var sessionLimitServiceMock, q;
beforeEach(inject(function (_SessionLimitService_, _SessionLimitResository_, $httpBackend, $rootScope) {
sessionLimitServiceMock = _SessionLimitService_;
//remove the use of global variables
$httpBackend.when('GET', serviceURL)
.respond('foo', {/*Headers*/});
}));
it("Content array must be empty", function () {
expect(sessionLimitServiceMock.content.length).toEqual(0);
});
it('Content array must have a value', function() {
$httpBackend.expectGET(serviceURL);
sessionLimitServiceMock.getData().then(function(value) {
expect(value).toEqual('foo'); // NOTHING HAPPENS
});
$httpBackend.flush();
});
});
4 Comments
Grendizer
Thanks for your reply. I get value as undefined in the above example. Pls see the edit above.
Raulucco
Yep, right it is
$httpBackend.flush() instead of $scope.$digest() according to docs. I'll update the exampleGrendizer
Hi again! I'm still getting the value as undefined...I updated the code above again...
Raulucco
I updated the code . I forgot to use
$httpBackend.expectGET. It is good to add an afterEach too as on the docs: ` afterEach(function() { $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); });`
$scope.$digest()this must be call manually when using $httpBackend module. I suggest you use $httpBackend to mock the ajax call and then$scope.digest