本文介绍了Angular 4 Unit测试错误 - 无法在'XMLHttpRequest'上执行'send':无法加载'ng:///DynamicTestModule/LoginComponent.ngfactory.js'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的组件编写一些单元测试,我收到了这个神秘的错误消息。我在但答案并没有帮助我解决我的问题。我很有棱角4.3.2

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

这是测试文件:

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

运行测试时,我在chrome控制台上获得以下内容:

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

任何可以帮助我?

编辑 - 1
这是服务/存根实现

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

编辑2
将我的TestBed配置更改为以下内容删除了错误但带来了一个新错误:

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

现在错误信息是

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
}


推荐答案

这是 Angular Cli 版本 1.2.2或更新版的问题。使用 - sourcemaps = false 运行测试,您将收到正确的错误消息。

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.

编辑

的缩写是:

详情请见:

这篇关于Angular 4 Unit测试错误 - 无法在'XMLHttpRequest'上执行'send':无法加载'ng:///DynamicTestModule/LoginComponent.ngfactory.js'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 07:01