1
Hello,
I have an application in Angularjs and I wanted to ensure the quality of my code by doing unit tests and I am using Karma and Jasmine for this. After having had a certain difficulty to configure the dependency injections and etc finally managed to "access" the functions of my controller and perform the tests. but I’m having trouble making the tests of the previous ones , I’m not able to find how to simulate the return of the asynchronous call to be able to continue with the test of my function.
will anyone know how to give me help?
This is my Service:
angular.module('projetoServices', [])
.factory('projetoService', ['$http', function ($http) {
return {
consultaLink: function (entrada) {
return $http.post('http://localhost:7001', entrada})
.then(tratarResposta, tratarErro);
},
};
function tratarResposta(response) {
if (response.data.data == null) {
return response.data;
} else {
return response.data.data;
}
}
function tratarErro(error) {
if (error.data.data == null) {
return error.data;
} else {
return error.data.data;
}
}
}]);
Follow function within my controller that I want to test:
vm = this;
vm.abreLink = abreLink;
function abreLink(id) {
projetoService.consultaLink({ "id": id}).then(function (response) {
if (response) {
var html = response.url;
$window.open(html, '_Blank',);
}
});
}
Within my test class I am injecting my service through the moduleCommonsInit file
(function (angular) {
angular.mock.moduleCommonsInit = function () {
module(function ($provide) {
$provide.factory('projetoService', function ($q) {
return {
consultaLink: function () {
var defer = $q.defer();
defer.resolve({ id: 1, url: www.alura.com.br });
return defer.promise;
},
};
});
});
};
}(angular));
and this is my test:
describe('testes da projeto
Controller', function () {
var $rootScope, $scope, $q, $httpBackend, $controller, vm;
beforeEach(function () {
angular.mock.moduleCommonsInit();
angular.mock.module('projeto
Controllers');
});
beforeEach(inject(function (_$rootScope_, _$controller_, _$q_,_$httpBackend_, projetoService) {
$q = _$q_;
$rootScope = _$rootScope_;
$scope = _$rootScope_.$new();
$httpBackend = _$httpBackend_;
$controller = _$controller_;
vm = _$controller_('projetoController', {
$scope: $scope,
projetoService : projetoService
});
}));
it('Teste AbreLink()...', function () {
var id = "1";
vm.abreLink(id);
});
});
Hello Sergio, First thank you for the suggestion. I tried to make the suggested change, ran my test but still the Coverage report only appears as covered by test until the "projectService.query"codeConfigurationInteration": codeLink }). then" and does not run through anything of the callback function that follows this . then thanks for the help, but my problem still persists.
– Rafael Silva