首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Angular 4 Karma组件测试因CORS问题失败

Angular 4 Karma组件测试因CORS问题失败
EN

Stack Overflow用户
提问于 2017-09-04 20:41:03
回答 3查看 12.3K关注 0票数 26

当我运行ng test时,当我尝试测试组件时得到这个错误(我在Karma中使用标准设置):

XMLHttpRequest cannot load ng:///DynamicTestModule/FullModalHeaderComponent.ngfactory.js. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

我如何解决这个问题?

代码:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { FullModalHeaderComponent } from './full-modal-header.component';

describe('FullModalHeaderComponent', () => {
  let component: FullModalHeaderComponent;
  let fixture: ComponentFixture<FullModalHeaderComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [FullModalHeaderComponent]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(FullModalHeaderComponent);
    fixture.detectChanges();
  });

  it('should be created', () => {
    expect(component).toBeTruthy();
  });
});

import { Component, Input } from '@angular/core';
import { ProcessingCenter, Publication } from '../../publications/model';

@Component({
  selector: 'gom-full-modal-header',
  templateUrl: './full-modal-header.component.html'
})
export class FullModalHeaderComponent {

  @Input('processingCenter') processingCenter: ProcessingCenter;
  @Input('publication') publication: Publication;
  @Input('title') title: string;

}

此外,当我使用ng test --sourcemaps=false运行测试时,问题也消失了。

EN

回答 3

Stack Overflow用户

发布于 2018-05-30 09:35:20

当存在未初始化的@Input时,组件测试可能会失败,并显示此错误。

为所有@Input属性提供合理的默认值:

@Input('processingCenter') processingCenter: ProcessingCenter = null;
@Input('publication') publication: Publication = null;
@Input('title') title: string = '';

或者确保在测试中初始化它们:

it('should be created', () => {
  component.processingCenter = new ProcessingCenter();
  component.publication = new Publication();
  component.title = 'The Title';
  expect(component).toBeTruthy();
});
票数 14
EN

Stack Overflow用户

发布于 2018-05-18 06:22:35

这也发生在我身上。对于任何通过Google到达这里的人来说,如果你已经从CLI中弹出了你的Angular项目,我通过编辑angular-cli.json并将ejected标记为false来解决这个问题。

在那之后,我能够运行上面的建议,并找出我真正的错误消息。

对我来说,这是我的组件模板的一部分,它利用了单元测试中未定义的注入服务。

票数 2
EN

Stack Overflow用户

发布于 2019-03-07 17:05:41

它是由失败的案例引起的。我们想要解决的真正问题是修复错误,而不是隐藏它。

尝试使用我的解决方案Solution to fix your Angular 5 – TestBed bug of XMLHttpRequest cannot load ng:///DynamicTestModule/-

有了我的修复,就不需要禁用sourcemap,真正的调试信息就会显示出来。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46037328

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档