Angular Testing: Mocking $ httpBackend - Handling Success and Errors
Update: I was able to narrow down the problem and fix the Unexpected Request error by updating the httpBackend.when request that contained some invalid ascii characters.
I added Plunker with its current codeblock .
But I still find it difficult to effectively test triggering successes and errors. I also need to add waits to check for broadcast messages.
To test the above scenario, I developed a hack that I included in Plunker, but I believe there must be a much better way to test these scenarios.
Any conclusions on how I can overcome this issue and check the response status would be greatly appreciated.
Problem
I have set the expected value / response for $ httpBackend for my test, but when I run $ httpBackend.flush () it doesn't show below mention error.
Error message specified
Error: Unexpected request: GET https://192.168.1.10:3334/res?t1=CHECK&t2='?'&req={"_msgType":"Login_msg","UserName":"e@e.com","Password":"123"}
I found helpful links that discussed about this problem domain, and they helped me narrow down the problem a bit. But I still can't figure out why this unit test is failing.
Useful questions
- Angular mock $ httpBackend gives no pending cleanup request
- Unit testing AngularJS with $ httpBackend gives "Error: Unexpected request"
- Testing Angular $ Resource with External Service
- Why am I getting the error ... unexpected request
- Mocking $ httpBackend
Useful external resources
- AngularJS tests with HTTP mock
- Unit Testing $ http service in Angular.js
- Angularjs Tutorial: Testing with ngMock $ httpBackend and Karma.
- Angular JS - Device Testing - Services
- AngularJS tests with HTTP mock
I also tried moving the flush () call around and also tried calling $ apply or $ digest when making a request to $ http in the test suggested here.
AngularJS Testing Service
app.service('restService',['$log','$http','$rootScope',function($log,$http,$rootScope)
{
this.location = null;
this.port = null;
this.sendRequest = function(host,port,param1,param2,requestMsg)
{
this.location = host;
this.port = port;
$http.get('https://'+host+":"+port+"/res?t1="+param1+"&t2="+param2+"&req="+JSON.stringify(requestMsg)).
success(function(data) {
//Need to add expectations to check success operations
$log.log('response received',data);
var msgData = data;
$rootScope.successCalled = true;
$rootScope.response = data;
if(msgData.hasOwnProperty('_msgType'))
{
$log.log('broadcast for channel',msgData._msgType);
$rootScope.$broadcast(msgData._msgType,msgData);
}
}).
error(function(){
//Need to add expectations to check error method operations
var httpErrMsg = {_msgType:'HTTPErr', host:host, port:port, t1:param1, t2:param2, requestMsg:requestMsg};
$rootScope.errorCalled = true;
$rootScope.response = data;
$rootScope.$broadcast(httpErrMsg._msgType,httpErrMsg);
});
}
this.getIP = function()
{
return this.location;
}
this.getPort = function()
{
return this.port;
}
}])
Characteristics used to test the service
"use strict";
describe("Rest service test", function()
{
var $scope, $location, httpBackend, $log, restService , loginMsg ;
beforeEach(module('app'));
beforeEach(inject(function (_restService_)
{
restService = _restService_;
}));
beforeEach(inject(function($rootScope, _$location_, $httpBackend, _$log_)
{
$scope = $rootScope.$new();
$location = _$location_;
httpBackend = $httpBackend;
$log = _$log_;
loginMsg={ _msgType:"Login_msg", UserName:"e@e.com", Password:"123"};
}));
afterEach(function()
{
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
describe("Service : Rest Service", function()
{
it('Should start with location and port undefined', function() {
expect(restService.location).toEqual(null);
expect(restService.port).toEqual(null);
});
it("check if method exists", function() {
expect(restService.sendRequest).toBeDefined();
});
it("GetIP method Exists ", function()
{
expect(restService.getIP).toBeDefined();
});
it("GetPort method Exists ", function()
{
expect(restService.getPort).toBeDefined();
});
it("GetIP Value ", function()
{
restService.location = '192.168.1.10';
expect(restService.location).toEqual('192.168.1.10');
});
it("GetPort Value ", function()
{
restService.port = '3334';
expect(restService.port).toEqual('3334');
});
it("Execute sendRequest()", function() {
httpBackend.when('GET', 'https://192.168.1.10:3334/res?t1=CHECK&t2=\'?\'&req={"_msgType":"Login_msg","UserName":"e@e.com","Password":"123"}')
.respond ({SessionId:"2103337586",Status:"user e@e.com not found ",EMail:"e@e.com",rejectCode:1,rejectReason:"Invalid username or password",_msgType:"LoginReply_msg"});
restService.sendRequest("192.168.1.10","3334","CHECK","'?'",loginMsg);
httpBackend.flush();
expect(restService.location).toEqual('192.168.1.10');
expect(restService.port).toEqual('3334');
expect($scope.successCalled).toBe(true);
expect($scope.response).not.toBe(null);
expect($scope.response._msgType).toEqual('LoginReply_msg');
});
});
});
source to share
I know this question is old, but maybe someone is looking, this might be helpful.
change your beforeEach function like this:
beforeEach(inject(function($rootScope, _$location_, $httpBackend, _$log_)
{
$scope = $rootScope.$new();
$location = _$location_;
httpBackend = $httpBackend;
$log = _$log_;
loginMsg={ _msgType:"Login_msg", UserName:"e@e.com", Password:"123"};
httpBackend.expectGET(/192.168.1.10:3334/i).respond(function (){
return [/*mockResponse*/];
});
}));
this will fix this error.
source to share