0

I'm trying to unit test my app built on Angular with Jasmine via Karma. The app involves making a call to the GitHub API and pulling the names of all the repos of a user and filling an array with those names. I'm trying to test that the array is getting filled but I'm having some issues with $httpBackend.

The relevant parts of my controller are:

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);
    };
  };

}]);

My RepoSearch factory is:

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
        }
      });
    }
  };

}]);

And the test in question is this:

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"]);
    });

  });

});

When I run the test I get the error

Expected [ ] to equal [ 'test1', 'test2' ].

So evidently this is because self.gitRepoNames is not being filled. When I console log ctrl.repoSearchResult just before the expectation in the test I get

Object{data: [Object{name: ...}, Object{name: ...}]}

Which is where the problem is I feel since self.repoSearchResult.length will be undefined when it is called in the for loop in the addRepoNames function.

So my question is why doesn't response.data return an array when it is called in the addRepoNames function in the test?

Any help would be greatly appreciated.

EDIT: I should mention that the app works fine when run on the server.

dbatten
  • 437
  • 5
  • 18

1 Answers1

0

ctrl.doSearch is an asynchronous function. You should handle it in an async way. Try:

it('adds search results to array of repo names', function(done) {
  ctrl.username = 'hello';
  ctrl.doSearch().then(function() {
    expect(ctrl.gitRepoNames).toEqual(["test1", "test2"]);
    done();
  });
  httpBackend.flush();      
});
Yaron Schwimmer
  • 5,327
  • 5
  • 36
  • 59
  • hi @yarons thanks for you reply. i've modified the test as per your response (with a `setTimeout` on `done()` as it was causing issues with `$digest`) but i'm still getting the same issue. – dbatten Dec 10 '15 at 15:56
  • why `setTimeout`? what was the issue with `$digest`? – Yaron Schwimmer Dec 10 '15 at 16:39
  • i was getting a `$digest already in progress`. from what i've read using `done()` and `httpBackend.flush()` together often causes issues. i referred to [this question](http://stackoverflow.com/questions/24341544/getting-digest-already-in-progress-in-async-test-with-jasmine-2-0) – dbatten Dec 10 '15 at 16:46
  • I never had this problem. That's weird. – Yaron Schwimmer Dec 10 '15 at 20:09