当我运行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
运行测试时,问题也消失了。
发布于 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();
});
发布于 2018-05-18 06:22:35
这也发生在我身上。对于任何通过Google到达这里的人来说,如果你已经从CLI中弹出了你的Angular项目,我通过编辑angular-cli.json并将ejected标记为false来解决这个问题。
在那之后,我能够运行上面的建议,并找出我真正的错误消息。
对我来说,这是我的组件模板的一部分,它利用了单元测试中未定义的注入服务。
发布于 2019-03-07 17:05:41
它是由失败的案例引起的。我们想要解决的真正问题是修复错误,而不是隐藏它。
尝试使用我的解决方案Solution to fix your Angular 5 – TestBed bug of XMLHttpRequest cannot load ng:///DynamicTestModule/-
有了我的修复,就不需要禁用sourcemap
,真正的调试信息就会显示出来。
https://stackoverflow.com/questions/46037328
复制相似问题