Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 Karma component test fail due to CORS issue

Tags:

angular

when I run ng test I get this error (I use standard setup with Karma) when I try to test component:

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

How can I address this issue?

Code:

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();   }); }); 

and

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;  } 

Also, when I run tests with ng test --sourcemaps=false issue goes away.

like image 960
dragonfly Avatar asked Sep 04 '17 12:09

dragonfly


1 Answers

This can also happen if you have something like this:

  • Your constructor or onInit calls a service
  • That service is faked/mocked so that it returns a result
  • The subscription on your service sets a property on your component
  • The component html has an error, for example:
    <strong>{{ result.item.subproperty }}</strong>     <!--             ^^^^^^                    -->     <!--      ^ could be null in tests ^       --> 

Note that if item is undefined because your fake/mock didn't have it, the component template will cause an exception, indirectly causing this problem.

So check your html for this type of problem, and fix your fake/mock and/or make your template more robust.

like image 180
Jeroen Avatar answered Sep 17 '22 16:09

Jeroen