Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS / Karma unit testing with real XHR data / passThrough()

I would like to use real $http data for my unit test using passThrough().

Here's what I have so far:

var should = chai.should();
beforeEach(module('myApp', 'ngMockE2E'));
beforeEach(inject(function(_$httpBackend_, _$rootScope_, _$http_) {
  $scope = _$rootScope_;
  $http = _$http_;
  $httpBackend = _$httpBackend_;
}));

it.only('blah', function(done) {
 $httpBackend.whenGET('/api/data').passThrough();

  $scope.$apply(function() {
  $http.get('/api/data').success(function(data) {
   data.should.eql({"foo": "bar"});
    done();
  });
});

// Evidently not required with E2E
//$httpBackend.flush();

});

But this gives an error:

Unexpected request: GET /api/data
No more request expected
Error: Unexpected request: GET /api/data
No more request expected

If I remove the apply call it times out.

like image 946
cyberwombat Avatar asked Nov 01 '22 11:11

cyberwombat


1 Answers

Most likely you would be running karma on a different port than the port where the services with real data are available. If you could re-route your requests to the server/port where the services with real data are running, such that it does not encounter CORS, you will be able to make it work. In my project, I use Charles proxy to map urls to get around CORS when using passThrough(). You can also make your real data services CORS compatible to ease things up.

like image 124
Nitesh Kumar Anand Avatar answered Nov 11 '22 13:11

Nitesh Kumar Anand