噶单元测交域资源AngularJS(Karma unit test cross domain res

2019-09-26 10:15发布

我使用的业力作为我的角度项目试运行的框架,我的角有服务器服务需要访问其他网页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安装插件因缘果报铬发射,并添加--disable-web-security在我的配置文件。 但它不工作。 2个set'Access-控制允许Origin''Access控制允许-Headers''Access-控制允许的方法在标题,以允许在服务器响应起源的访问。

所有以上不工作,那么如何解决我的问题?

Answer 1:

对于跨域请求使用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();
    });
});

来源为这个例子



文章来源: Karma unit test cross domain resource AngularJS