I'm currently in the process of writing unit tests for my Angular app using Jasmine with Karma. One of the functionalities of the app is to make a call to the GitHub API, retrieve a user's repository names, and store them in an array. Although I'm attempting to test that the array gets populated successfully, I'm encountering difficulties with $httpBackend.
The essential sections of my controller are as follows:
readmeSearch.controller('ReadMeSearchController', ['RepoSearch', function(RepoSearch) {
var self = this;
self.gitRepoNames = [];
self.doSearch = function() {
var namesPromise =
RepoSearch.query(self.username)
.then(function(repoResponse) {
addRepoNames(repoResponse);
}).catch(function(error) {
console.log('error: ' + error);
});
return namesPromise;
};
addRepoNames = function(response) {
self.repoSearchResult = response.data;
for(var i = 0; i < self.repoSearchResult.length; i++) {
var name = self.repoSearchResult[i]['name']
self.gitRepoNames.push(name);
};
};
}]);
The RepoSearch factory is defined as:
readmeSearch.factory('RepoSearch', ['$http', function($http) {
return {
query: function(searchTerm) {
return $http({
url: 'https://api.github.com/users/' + searchTerm + '/repos',
method: 'GET',
params: {
'access_token': gitAccessToken
}
});
}
};
}]);
Additionally, the relevant test code is provided below:
describe('ReadMeSearchController', function() {
beforeEach(module('ReadMeter'));
var ctrl;
beforeEach(inject(function($controller) {
ctrl = $controller('ReadMeSearchController');
}));
describe('when searching for a user\'s repos', function() {
var httpBackend;
beforeEach(inject(function($httpBackend) {
httpBackend = $httpBackend
httpBackend
.expectGET('https://api.github.com/users/hello/repos?access_token=' + gitAccessToken)
.respond(
{ data: items }
);
}));
afterEach(function() {
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
var items = [
{
"name": "test1"
},
{
"name": "test2"
}
];
it('adds search results to array of repo names', function() {
ctrl.username = 'hello';
ctrl.doSearch();
httpBackend.flush();
expect(ctrl.gitRepoNames).toEqual(["test1", "test2"]);
});
});
});
Upon running the test, I encounter the following error:
Expected [ ] to equal [ 'test1', 'test2' ].
The issue seems to stem from self.gitRepoNames
not being populated. Prior to the expectation in the test, when I log ctrl.repoSearchResult
, I receive:
Object{data: [Object{name: ...}, Object{name: ...}]}
This leads me to believe that the problem lies in the fact that self.repoSearchResult.length
is undefined when accessed within the for loop of the addRepoNames
function.
Hence, my question is why does response.data
not return an array when invoked in the addRepoNames
function during the test?
Any assistance on this matter would be greatly appreciated.
EDIT: It's worth noting that the app functions correctly when executed on the server.