1

我使用 karma 作为我的 Angular 项目测试运行框架,我的 Angular 有服务器服务需要访问另一个 Web url 来获取数据,比如http://localhost:8081/common/countries获取有关国家/地区的所有信息。我的问题是我的业力开始于localhost:9876它需要http://localhost:8081/common/countries通过浏览同源策略从这个导致跨域问题中获取数据。所以我在控制台中收到以下错误:

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) 

我尝试过: 1 安装业力插件 karma-chrome-launcher 并添加--disable-web-security到我的配置文件中。但它不起作用。2 在标头中设置'Access-Control-Allow-Origin''Access-Control-Allow-Headers''Access-Control-Allow-Methods'以允许服务器响应中的源访问。

以上都不起作用,那么如何解决我的问题?

4

1 回答 1

0

对于跨域请求,请使用expectJSONP并确保使用回调参数。

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

此示例的来源

于 2013-10-21T02:57:47.747 回答