jeudi 9 avril 2015

Write tests for an angular REST app

I'm a beginner and trying to learn how to write test for a REST Angular app. I've been clueless so far. Say I have this very simple app module:



var app = angular.module('myApp', []);

app.constant('config', {
CLIENT_ID:'123',
CLIENT_SECRET:'123'
});

app.service('searchService', ['$http','config', function($http,config){
var baseURL;
var buildBaseURL=function(client_id,client_secret){
return "http://ift.tt/1Js2nkC"+
"?client_id="+client_id+
"&client_secret="+client_secret+
"&query=";
}
baseURL=buildBaseURL(config.CLIENT_ID,config.CLIENT_SECRET);
return {
search: function(query){
return $http.get(baseURL+query);
}
};
}]);

app.controller('mainCtrl', ['$scope','searchService',function($scope, searchService) {
searchService.search($scope.searchWords).success(function(data) {
$scope.responseData=data;
});
}]);


It works on the browser. Now I tried to test it using karma, mocha & chai. Say I want to write a test case to test the success path of the request. How should I write that? Here is what I'm trying sofar:



describe('',function(){
var $httpBackend = null;
var locationService = null;

beforeEach(function(){
module('myApp');
inject(function(_$httpBackend_,_locationService_){
$httpBackend = _$httpBackend_;
locationService = _locationService_;
});
});

it('test case 1',function(){
var searchWord = 'car';
$httpBackend.expectGET(searchWord);
var result;
locationService.search(searchWord).success(function(data) {
result=data.response.venues;
});
console.log(result); //undefined
$httpBackend.flush();
});

});


All it returned is just:



"Unexpected request: GET http://ift.tt/1Js2nkC .... etc
Expected GET car
$httpBackend@http://ift.tt/1GsHaZs
sendReq@http://ift.tt/1Js2pJl
$http/serverRequest@http://ift.tt/1GsHdo4
qFactory/defer/deferred.promise.then/wrappedCallback@http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js:11319:31
... etc
Firefox 37.0.0 (Ubuntu): Executed 1 of 1 (1 FAILED) ERROR (0.034 secs / 0.004 secs)

Aucun commentaire:

Enregistrer un commentaire