I'm trying to test my Authentication Service, which is (among others) responsible for registering a new user with my API.
For the sake of simplicity, my code to be tested looks simply like this:
register: function (user) {
return $
http.post('/api/register', user);
}
So it simply sends an HTTP POST and returns the according promise.
To unit test it, I have to mock the XHR call, so that it gets the answer I expect, so that I can test the behavior. Therefore, I access the $httpBackend like:
var $httpBackend;
beforeEach(inject(function(_$httpBackend_) {
$httpBackend = _$httpBackend_;
}));
Pretty easy so far.
So in my test specification (Jasmine), I tell the $httpBackend what I expect. The API will simply return the registered user in case of success (which is the test scenario). Then I call the register function from above and flush the whole thing:
var mockUser = {
username: 'johndoe'
}
$httpBackend.expectPOST('/api/register, mockUser).respond(200, mockUser);
var mockUser = {
username: 'johndoe'
}
var authService = $injector.get('AuthenticationService'); // initiate here so that the service uses my $httpBackend? have read that somewhere
authService.register(mockUser ).then( // No testing so far
function () {
console.log("Success");
},
function () {
console.log("Error");
}
);
$httpBackend.flush(); // Flush after the http post should resolve the promise!
The Error Message Karma displays is:
Error: No pending request to flush !
at Error (<anonymous>)
at Function.$httpBackend.flush (%my_dir%/test/lib/angular/angular-mocks.js:1171:34)
at null.<anonymous> (%my_dir%/test/unit/services/authenticationSpec.js:45:16)
at Object.invoke (%my_dir%/app/js/vendor/angular/angular.js:2931:28)
at workFn (%my_dir%/test/lib/angular/angular-mocks.js:1758:20)
Error: Declaration Location
at window.jasmine.window.inject.angular.mock.inject (%my_dir%/test/lib/angular/angular-mocks.js:1744:25)
at null.<anonymous> (%my_dir%/test/unit/services/authenticationSpec.js:17:67)
at /%my_dir%/test/unit/services/authenticationSpec.js:1:1
(I just replaced my complete path prefix with %my_dir% ;)
Anyone out there who can help me and tell me how to do that right?