Подтвердить что ты не робот

Angular 4 Unit test error - Не удалось выполнить 'send' on 'XMLHttpRequest': Не удалось загрузить 'ng:///DynamicTestModule/LoginComponent.ngfactory.js'

Я пишу некоторые модульные тесты для моего компонента, и я получаю это загадочное сообщение об ошибке. Я нашел аналогичный вопрос в Angular 2 модульных тестах - получение ошибки Не удалось загрузить 'ng:///DynamicTestModule/module.ngfactory.js', но ответы не помогите мне решить мою проблему. Я angular 4.3.2

Здесь компонент я пишу тест для:

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

И вот тестовый файл:

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

При запуске теста я получаю следующее на консоли хром:

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] (

Кто-нибудь может мне помочь?

РЕДАКТИРОВАТЬ - 1 Здесь реализация сервисов/заглушек

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

РЕДАКТИРОВАТЬ 2 Меняя конфигурацию TestBed на следующую, удалила ошибку, но принесла новую:

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

Теперь сообщение об ошибке

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)

Что происходит при этой функции:

function resetFakeAsyncZone() {
    _fakeAsyncTestZoneSpec = null;
    ProxyZoneSpec.assertPresent().resetDelegate(); //ProxyZoneSpec is undefined here for whatever reason
}
4b9b3361

Ответ 1

Это проблема с версией Angular Cli 1.2.2 или более новой. Запустите тест с помощью --sourcemaps=false, и вы получите правильные сообщения об ошибках.

ng test --sourcemaps = false

ИЗМЕНИТЬ

сокращенное обозначение:

ng test -sm = false

Подробнее здесь: https://github.com/angular/angular-cli/issues/7296

Ответ 2

Я просто столкнулся с этой ошибкой, и проблема была в моих маках. В компоненте .ngOnInit я использовал this.route.paramMap.subscribe(...) где маршрут является экземпляром ActivatedRoute

В моем тесте я предоставил макет службы следующим образом:

providers: [
    { provide: ActivatedRoute, useValue: { snapshot: { params: { id: 1 } } } }
]

И на самом деле я пропустил, чтобы высмеять метод paramMap

Затем я исправлю его добавлением свойств paramMap, подобных этому

providers: [
    { provide: ActivatedRoute, useValue: { snapshot: { params: { id: 1 } }, paramMap: Observable.of({get: () => 1}) } }
]

Тогда у меня больше нет этой глупой ошибки.

Итак, для вас, я ожидаю, что класс SessionServiceStub будет неполным или ошибочным. Получает ли он метод входа, который возвращает Observable?

Если это не проблема, вы можете проверить NotificationServiceStub

Вам следует использовать отладчик (с помощью Webstorm, который легко отлаживать поэтапно), чтобы помочь вам.