Angular 4 Karma component test fail due to CORS issue

karma cors error
has been blocked by cors policy angular
angular cross origin request blocked
access to xmlhttprequest at from origin has been blocked by cors policy angular 6

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.

Component tests can fail with this error when there is an uninitialised @Input.

Provide sensible defaults for all your @Input properties:

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

Or make sure to initialise them in your tests:

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

Angular 4 Karma component test fail due to CORS issue, when I run ng test I get this error (I use standard setup with Karma) when I try to test component: XMLHttpRequest cannot load  The test itself: I removed the @Injectable tag in the hopes that it would isolate angular from the issue. The test "LocationService Lat/Lon to tile conversion should match for the two lat2TileY functions" (the last test) is the one that passes in the command line but fails in the debugger.

Angular 4 Karma component test fail due to CORS issue, Component tests can fail with this error when there is an uninitialised @Input . Provide sensible defaults for all your @Input properties: Dismiss Join GitHub today. GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.

This happened to me as well. For anyone who arrives here via Google, if you have ejected your Angular project out of the CLI, I resolved this by editing the angular-cli.json and marking ejected false.

After that, I was able to run the suggestion above and find out my real error message.

For me, it was a piece of my component template that was making use of an injected service that was undefined in my unit test.

Regression wrong error message during tests if runtime error occurs , JSMike opened this issue on Aug 7, 2017 · 56 comments @nathanBrenner thanks, disabling sourcemaps for unit tests lets me now I have some component with exception and I get error like topic started mentioned. Bug: Angular CLI test running module build/chrome concurrently #7657 which triggers CORS errors. Unfortunately, the behaviour of whenStable in Angular 4 is somewhat underministic. For some tests whenStable works fine under Angular 4 and in some other tests they don't. They tests that fail depend on lots of complex UI, so it is very difficult to create an independent test case.

I stumbled on this issue too. Here are the things to look for (Just consolidating all possibilities into one location). I resolved my issue using first and second steps

  1. Try ng test --source-map=false to see if there's an issue elsewhere.
  2. If the issue is resolved by simply adding --source-map=false and if you are using mock services that returns an observable, make sure subscribers have an error handler, then you do not need the source-map false flag

    this.fe.getData().subscribe(d => { ... }, err => console.log(err));

  3. Use safe navigators in your HTML

  4. Make sure component inputs are set in test env check @tanya's answer

[object ErrorEvent] thrown in angular app, Debug window. · Issue , There error itself is being thrown in zone.js/dist/zone.js: 195 , with zone.js /​46037328/angular-4-karma-component-test-fail-due-to-cors-issue. Unit Testing in Angular 4 Using Jasmine and Karma - Part 1 which can be broken due to any changes. How to unit test an Angular 4 component. How to unit test an Angular 4 directive.

It's caused by failed case(s). The real problem we want to address, is to fix the error, not hide it.

Try to use my solution Solution to fix your Angular 5 – TestBed bug of XMLHttpRequest cannot load ng:///DynamicTestModule/-

With my fix, there is no need to disable sourcemap and the real debugging info is revealed.

angular: Angular 4 Karma component test fail due to CORS issue, when I run ng test I get this error (I use standard setup with Karma) when I try to test component:XMLHttpRequest cannot load  Maybe the issue is not with the Angular CLI but rather with Firefox. With Angular CLI 1.4.4 I can successfully set breakpoints and debug TypeScript sources in Chrome, Safari and Edge. Only Firefox does not allow me to set breakpoints. Still, with Angular CLI 1.0.6 it is working in all browsers including Firefox.

HttpErrorResponse, Angular is a platform for building mobile and desktop web applications. 3. Create a Feature Component · 4 A response that represents an error or failure, either from a non-successful HTTP status, an error while executing the request, or some other failure which Stack Overflow · Gitter · Report Issues · Code of Conduct  This video is part of my advanced, full-featured AngularJS master course, learn more at https://ultimateangular.com

Testing, Refer to the Angular Testing Guide for detailed information on testing Angular Unit tests are contained in spec files with one spec file per entity (component, page, When the tax codes change, only the tax service related code and tests need to toEqual(true); }); it('displays an error message if the login fails', () => { login. source: angular/angular#23593 [ ] Regression (a behavior that used to work and stopped working in a new release) [X] Bug report [ ] Performance issue [ ] Feature request [ ] Documentation issue or

Angular 6: Using Karma for Unit Testing, Using RouterTestingModule to test Angular Router Object. Code to be tested; Karma/Jasmine Test Code; Potential Error. Using SpyOn to run  AngularJs Meetup South London Collection | this article. Angular was designed with testability in mind and it provides multiple options to support Unit Testing.In this article I will show you how you can setup Jasmine and write unit tests for your angular components.

Comments
  • Can you post your test code ? This is most probably coming from here
  • Sure, test code is generated from angular-cli
  • Can you try running ng test --sourcemaps=false and update the post ? This issue is most probably a fake one since there is no way this is a CORS issue. Also, can you post your HTML template code ? I think this is coming from here
  • Be sure to check for your template variables, the issue was coming from here. Most likely an input value not being instanciated when the test is running or something like that. Adding the safe navigation operator might just solve all the issues and you might not even need --sourcemaps=false anymore. exemple : {{entity.count}} ==> {{entity?.count}}
  • also look into that : github.com/angular/angular-cli/issues/7296
  • This didn't fix my issue but it is the correct reason for my issue. However, my situation is different from above. I think this should work for the current question.
  • This is a complete answer. In addition I had a TypeError for the same test complaining about no next being defined, perhaps because it was trying to iterate a field that did not exist.