Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 Unit test error - Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'ng:///DynamicTestModule/LoginComponent.ngfactory.js'

Tags:

I am writing some unit tests for my component and i am getting this cryptic error message. I found a similar question at Angular 2 unit testing - getting error Failed to load 'ng:///DynamicTestModule/module.ngfactory.js' but the answers did not help me solve my issue. I am angular 4.3.2

Here's the component i am writing the test for:

import {Component} from '@angular/core'; import {Router} from '@angular/router';  import {NotificationService} from '../common/notification/notification.service'; import {SessionService} from '../common/session/session.service'; import {Login} from './login.model';  @Component({              selector: 'cc-login-form',              templateUrl: './login.component.html',              styleUrls: ['./login.component.scss'],            }) export class LoginComponent {   model: Login = new Login('', '');    constructor(private sessionService: SessionService,               private router: Router,               private notificationService: NotificationService) {   }    onSubmit() {     this.sessionService         .login(this.model.email, this.model.password)         .subscribe(           sessionInfo => {             this.notificationService.showSuccess('notification.successfully.logged.in');             this.router.navigate([`/cc/list`]);           },           error => this.notificationService.showError('notification.invalid.login')         );   } } 

And here is the test file:

import {async, ComponentFixture, TestBed} from '@angular/core/testing'; import {FormsModule} from '@angular/forms'; import {Router} from '@angular/router'; import {TranslateModule, TranslateService} from '@ngx-translate/core'; import {NotificationService} from '../common/notification/notification.service'; import {NotificationServiceStub} from '../common/notification/tests/NotificationServiceStub'; import {SessionService} from '../common/session/session.service'; import {SessionServiceStub} from '../common/session/tests/SessionServiceStub'; import {RouterStub} from '../common/tests/RouterStub'; import {TranslateServiceStub} from '../common/translate/tests/TranslateServiceStub';  import {LoginComponent} from './login.component';  describe('LoginComponent', () => {   let component: LoginComponent;   let fixture: ComponentFixture<LoginComponent>;    beforeEach(async(() => {     TestBed.configureTestingModule({                                      imports: [                                        FormsModule,                                        TranslateModule                                      ],                                      declarations: [LoginComponent],                                      providers: [                                        {provide: SessionService, useClass: SessionServiceStub},                                        {provide: Router, useClass: RouterStub},                                        {provide: NotificationService, useClass: NotificationServiceStub},                                        {provide: TranslateService, useClass: TranslateServiceStub},                                      ]                                    })            .compileComponents();   }));    beforeEach(() => {     fixture = TestBed.createComponent(LoginComponent);     component = fixture.componentInstance;     fixture.detectChanges();   });    it('should be created', () => {     expect(component).toBeTruthy();   }); }); 

When running the test i get the following on chrome console:

zone.js:2642 XMLHttpRequest cannot load ng:///DynamicTestModule/LoginComponent.ngfactory.js. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https. (anonymous) @ zone.js:2642 zone.js:195 Uncaught DOMException: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'ng:///DynamicTestModule/LoginComponent.ngfactory.js'.     at http://localhost:9876/_karma_webpack_/webpack:/Users/pedrompg/Documents/quandoo/fe/chains-center/~/zone.js/dist/zone.js:2642:1     at XMLHttpRequest.proto.(anonymous function) [as send] ( 

Any can help me with that?

EDIT - 1 Here's the services/stubs implementation

SessionServiceStub

export class SessionServiceStub implements ISessionService {   login(login: string, password: string): Observable<any> {     return Observable.of({merchantId: 123});   }    logout(): Observable<any> {     throw new Error('Method not implemented.');   }    validateSessionToken(): Observable<any> {     throw new Error('Method not implemented.');   } } 

SessionService

@Injectable() export class SessionService implements ISessionService {    constructor(private http: CcHttpClient, private router: Router, private localSessionService: LocalSessionService) {   }    login(login: string, password: string): Observable<any> {     return this.http.post(`api/sessions`, {login: login, password: password}).map((res: Object) => {       this.localSessionService.createSession(res);       return res;     });   } } 

RouterStub

export class RouterStub {   navigate(commands: any[], extras?: NavigationExtras): Promise<boolean> {     return Promise.resolve(true);   }; } 

TranslationServiceStub

export class TranslateServiceStub {   instant(key: string | Array<string>, interpolateParams?: Object): string | any {     return 'translation';   }; } 

NotificationServiceStub

export class NotificationServiceStub implements INotificationService {   showToast(type, text, title, defaultTitle): Promise<Toast> {     return Promise.resolve(null);   }    showSuccess(msg, title?): Promise<Toast> {     return Promise.resolve(null);   }    showError(msg, title?): Promise<Toast> {     return Promise.resolve(null);   } } 

EDIT 2 Changing my TestBed config to the following removed the error but brought a new one:

beforeEach(async(() => {     TestBed.configureTestingModule({                                      imports: [                                        FormsModule,                                        HttpClientModule,                                        TranslateModule.forRoot({                                                                  loader: {                                                                    provide: TranslateLoader,                                                                    useFactory: HttpTranslateLoaderFactory,                                                                    deps: [HttpClient]                                                                  }                                                                })                                      ],                                      declarations: [LoginComponent],                                      providers: [                                        {provide: SessionService, useClass: SessionServiceStub},                                        {provide: Router, useClass: RouterStub},                                        {provide: NotificationService, useClass: NotificationServiceStub},                                      ]                                    })            .compileComponents();   })); 

Now the error message is

TypeError: Cannot read property 'assertPresent' of undefined         at resetFakeAsyncZone home/pedrompg/Documents/quandoo/fe/chains-center/~/@angular/core/@angular/core/testing.es5.js:304:1)         at Object.<anonymous> home/pedrompg/Documents/quandoo/fe/chains-center/~/@angular/core/@angular/core/testing.es5.js:1001:1)         at ZoneQueueRunner.webpackJsonp.../../../../zone.js/dist/jasmine-patch.js.jasmine.QueueRunner.ZoneQueueRunner.execute home/pedrompg/Documents/quandoo/fe/chains-center/~/zone.js/dist/jasmine-patch.js:132:1) 

Which happens at this function:

function resetFakeAsyncZone() {     _fakeAsyncTestZoneSpec = null;     ProxyZoneSpec.assertPresent().resetDelegate(); //ProxyZoneSpec is undefined here for whatever reason } 
like image 546
Pedro Garcia Mota Avatar asked Aug 07 '17 16:08

Pedro Garcia Mota


1 Answers

This is a problem with the Angular Cli version 1.2.2 or newer. Run your test with --sourcemaps=false and you will get the right error messages.

In Angular 4-5

  • ng test --sourcemaps=false 
    or
  • ng test -sm=false 

In Angular 6+

  • ng test --source-map=false 

See details here: https://github.com/angular/angular-cli/issues/7296

like image 91
yugantar kumar Avatar answered Sep 21 '22 11:09

yugantar kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!