【问题标题】:getting CORS error when running Jasmine and Karma in Angular在 Angular 中运行 Jasmine 和 Karma 时出现 CORS 错误
【发布时间】:2019-06-03 10:22:59
【问题描述】:

我正在运行 specs 并注意到浏览器窗口中出现以下错误

zone.js:2990 Access to XMLHttpRequest at 'ng:///DynamicTestModule/NewPracticeQuestionComponent_Host.ngfactory.js' from origin 'http://localhost:9876' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

我想在我的应用程序的某个地方,已经发出了一些消息,这导致了CORS 问题。我假设它是 Karma 使用的 Web 服务器,它阻止了请求。

我可以将Karma 配置为禁用CORS 策略吗?

【问题讨论】:

标签: cors karma-jasmine


【解决方案1】:

我得到了一个失败的完整测试夹具。查看控制台日志,它包含以下错误消息:

在“ng:///CompanyVehicleGridComponent.js”访问 XMLHttpRequest 来自原产地“http://localhost:9876”已被 CORS 政策阻止: 跨源请求仅支持协议方案:http, 数据、铬、铬扩展、铬不受信任、https。

我在 Angular 11 应用程序中使用 PrimeNG 控件。我正在使用显示和删除行的 PrimeNG 网格。然后在网格中,单击创建和编辑按钮将弹出 PrimeNG 模态对话框。我发现这种组件组合是一个有趣的测试挑战。下面对网格组件进行说明:

<!-- File: company-vehicle-grid.component.html -->
<div *ngIf='companyvehicles !== undefined'>
    <p-table id='companyvehicles-grid' [value]='companyvehicles'
        [totalRecords]='totalRecords' dataKey='VehicleId'
        [rows]='5' [paginator]='true' [rowsPerPageOptions]='[5,10,50]'>

        ...

    </p-table>
</div>
<!-- modal edit windows -->
<app-company-vehicle-detail-window [companyvehicle]='windowCompanyVehicleInput'
    (closeWin)='closeWin($event)'></app-company-vehicle-detail-window>
...
<!-- End of company-vehicle.grid.component.html -->

这个错误出现在网格测试结构中。运行以下测试指令:

ng test --source-map=false

没有帮助。我删除了 company-vehicle-detail-window 并且错误消失了,表明问题是由于模态对话框窗口的变化引起的。在实现PrimeNG模态对话框的过程中,我更改了一些导致错误的服务调用,需要添加到网格测试的mock spy服务中,这样模态对话框就可以通过构造函数和ngOnInit获取。

此外,我计划更改的一件事是,当我开发详细信息窗口时,我将描述设置为限制测试以仅测试一个结构,如下所示:

fdescribe( 'CompanyVehicleDetailWindowComponent', ( ) => {

我现在将网格设置为同时测试网格表单,所以在进行更改时我会看到错误。

【讨论】:

    【解决方案2】:

    使用--sourcemaps=false 运行您的测试,您将收到正确的错误消息。

    这是一个问题:https://github.com/angular/angular-cli/issues/7296

    还有,速记:

    ng test -sm=false
    

    从 Angular 6 开始,命令是:

    ng test --source-map=false
    

    【讨论】:

      【解决方案3】:

      我认为这不是 CORS 问题,除非您实际上是跨域调用某些东西。

      我在代码中设置日期的组件返回类似错误时遇到了类似问题。您可能没有在测试中设置一些必需的值,或者您没有在正确的位置调用 fixture.detectChanges()。

      尝试在运行 npm test(或 ng test)时将 --source-map 标志设置为 false,您实际上可能会得到更有意义的错误。

      除了错误消息之外发布受影响的代码通常是个好主意。

      干杯, 阿尔贝托

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-19
        • 2016-04-14
        • 2015-06-24
        • 2021-09-06
        • 2022-09-26
        • 2019-07-20
        • 2015-03-23
        • 2015-07-08
        相关资源
        最近更新 更多