gpt4 book ai didi

javascript - Karma单元测试跨域资源AngularJS

转载 作者:行者123 更新时间:2023-11-28 08:48:17 25 4
gpt4 key购买 nike

我使用 karma 作为我的 Angular 项目测试运行框架,我的 Angular 服务器服务需要访问另一个 Web url 来获取数据,例如 http://localhost:8081/common/countries 获取所有信息关于国家。我的问题是我的 karma 从 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 插件 karma-chrome-launcher 并在我的配置文件中添加 --disable-web-security 。但它不起作用。2 在 header 中设置'Access-Control-Allow-Origin''Access-Control-Allow-Headers''Access-Control-Allow-Methods'以允许服务器响应中的源访问。

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

最佳答案

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

Source for this example

关于javascript - Karma单元测试跨域资源AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19485067/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com