gpt4 book ai didi

javascript - Angular 4 单元测试错误 - 无法在 'send' : Failed to load 'XMLHttpRequest' 上执行 'ng:///DynamicTestModule/LoginComponent.ngfactory.js'

转载 作者:太空狗 更新时间:2023-10-29 16:53:06 25 4
gpt4 key购买 nike

我正在为我的组件编写一些单元测试,但我收到了这个神秘的错误消息。我在 Angular 2 unit testing - getting error Failed to load '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();
});
});

运行测试时,我在 chrome 控制台上得到以下信息:

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这是服务/ stub 实现

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

session 服务

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

最佳答案

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

在 Angular 4-5 中

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

在 Angular 6+ 中

  • >
    ng test --source-map=false

在此处查看详细信息:https://github.com/angular/angular-cli/issues/7296

关于javascript - Angular 4 单元测试错误 - 无法在 'send' : Failed to load 'XMLHttpRequest' 上执行 'ng:///DynamicTestModule/LoginComponent.ngfactory.js',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45551214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com