I use karma as my angular project test running framework, my angular have server service need to access another web url to get data like http://localhost:8081/common/countries get all information about country. my problem is my karma start at localhost:9876 and it need to get data from http://localhost:8081/common/countries this cause cross domain problem by the browse same-origin policy. so I get below error in my console:

Error: Unexpected request: GET http://localhost:8081/common/countries
No more request expected
    at Error (<anonymous>)
    at $httpBackend (http://localhost:9876/absoluteC:/WebUI/WebUI/test/lib/angular/angular-mocks.js:934:9)
    at sendReq (http://localhost:9876/absoluteC:/WebUI/WebUI/vendor/angular/angular.js:9087:9)
    at $http (http://localhost:9876/absoluteC:/WebUI/WebUI/vendor/angular/angular.js:8878:17)
    at Object.getMock (http://localhost:9876/base/share/services.js:644:17)
    at Object.get (http://localhost:9876/base/share/services.js:347:28)
    at Object.getCountries (http://localhost:9876/base/share/services.js:221:22)
    at Object.clSingleSelectConfig.nationality.getData (http://localhost:9876/base/share/directives.js:146:32)
    at http://localhost:9876/base/share/directives.js:192:44
    at nodeLinkFn (http://localhost:9876/absoluteC:/WebUI/WebUI/vendor/angular/angular.js:4360:13) 

What i have tried: 1 install karma plugin karma-chrome-launcher and add --disable-web-security in my config file. but it doesn't work. 2 set'Access-Control-Allow-Origin''Access-Control-Allow-Headers''Access-Control-Allow-Methods' in header to allow origin access in server response.

all above don't work, so how to solve my problem?

有帮助吗?

解决方案

For cross domain requests use expectJSONP and be sure to use a callback parameter.

describe('stackoverflow.activity tests', function () {
    var svc, httpBackend;

    beforeEach(function (){  
      module('ngResource');
      module('stackoverflow.activity');
      inject(function($httpBackend, StackoverflowActivityService) {
        svc = StackoverflowActivityService;      
        httpBackend = $httpBackend;
      });
    });

    afterEach(function() {
      httpBackend.verifyNoOutstandingExpectation();
      httpBackend.verifyNoOutstandingRequest();
    });

    it('should send the message and return the response', function (){
        var returnData = { testing: 'anything'};
        httpBackend.expectJSONP('http://api.stackexchange.com/2.1/users/gigablox/timeline?callback=JSON_CALLBACK').respond(returnData);
        svc.events({
            user:'gigablox',
            params:{
                callback:'JSON_CALLBACK'
            }
        }).get(function(user) {
            expect(user.testing).toEqual('anything');
        });
        httpBackend.flush();
    });
});

Source for this example

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top