Update: мне удалось еще более сузить сферу проблемы и исправить Неожиданный запрос ошибку обновив httpBackend.when запрос, содержащий некоторые недопустимые символы ascii.
Я приложил Plunker с его текущим кодовым блоком.
Но я все еще испытываю трудности в эффективном тестировании запуска операций успешных операций и ошибок. Мне также необходимо добавить ожидания для проверки трансляции сообщений.
Чтобы проверить вышеупомянутый сценарий, я разработал взлом, который я включил в Plunker, но я считаю, что должен быть намного лучший способ проверить эти сценарии.
Любые выводы о том, как я смогу преодолеть эту проблему и проверить статус ответа, будут высоко оценены.
Проблема
Я установил ожидаемое значение/ответ на $ httpBackend для моего теста, но когда я бегу $ httpBackend.flush(), он не указывает на ошибку ниже упоминания.
Сообщение об ошибке указано
Error: Unexpected request: GET https://192.168.1.10:3334/res?t1=CHECK&t2='?'&req={"_msgType":"Login_msg","UserName":"[email protected]","Password":"123"}
Я нашел некоторые полезные ссылки, обсужденные об этой проблемной области, и они помогают мне несколько сузить масштабы проблемы. Но я все еще не могу понять, почему именно этот модульный тест терпит неудачу.
Полезные Stack Overflow Questions
- Angular mock $httpBackend give No pending request to flush
- Unit testing AngularJS with $httpBackend gives “Error: Unexpected Request”
- Testing Angular $resource with external service
- Why do I receive error … unexpected request
- Mocking $httpBackend
Полезные внешние ресурсы
- AngularJS Tests With An HTTP Mock
- Unit Testing $http service in Angular.js
- Angularjs Tutorial: Testing using ngMock $httpBackend and karma.
- Angular JS - Unit Testing - Services
- AngularJS Tests With An HTTP Mock
Я также попытался moving the flush() call around, а также попробовал calling $apply or $digest при создании запроса на получение $ http в тесте, как предлагается здесь.
AngularJS Сервис для тестирования
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;
}
}])
функции используется для проверки службы
"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:"[email protected]", 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":"[email protected]","Password":"123"}')
.respond ({SessionId:"2103337586",Status:"user [email protected] not found ",EMail:"[email protected]",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');
});
});
});