gpt4 book ai didi

Angular 2 如何测试使用路由器的组件

转载 作者:行者123 更新时间:2023-12-02 18:26:10 26 4
gpt4 key购买 nike

我正在尝试为调用router.navigate()的组件编写一些测试,但我在声明路由时遇到了错误。我读过很多东西并尝试了所有这些,但它们都会导致一些错误。我正在使用 Angular 4.0.0。

组件:

@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
constructor(
private activatedRoute: ActivatedRoute,
private authService: AuthService,
private formBuilder: FormBuilder,
private jwtService: JwtService,
private router: Router,
private storageService: StorageService
) { ... }

ngOnInit() {
}

private login(formData: any): void {
const credentials: any = {
email: formData.controls.email.value,
password: formData.controls.password.value
};
this.authService.login(credentials).subscribe(res => {
this.activatedRoute.params.subscribe(params => {
if (params.returnUrl) {
this.router.navigate([params.returnUrl]);
} else {
this.router.navigate(['/dashboard']);
}
});
}, error => { ... });
}
}

测试:

describe('LoginComponent', () => {
let component: any;
let fixture: ComponentFixture<LoginComponent>;

beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ LoginComponent ],
imports: [
SharedModule,
RouterTestingModule
],
providers: [{
provide: AuthService,
useClass: MockAuthService
}, {
provide: JwtService,
useClass: MockJwtService
}, {
provide: StorageService,
useClass: MockStorageService
}],
schemas: [ NO_ERRORS_SCHEMA ]
})
.compileComponents();
}));

beforeEach(() => {
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});

describe('login', () => {
it('should call router.navigate with the dashboard route if the login is successful', () => {
spyOn(component.router, 'navigate');
component.authService.login.and.returnValue(Observable.of({ access_token: 'fake_token' }));
component.login(component.loginForm);
expect(component.router.navigate).toHaveBeenCalledWith(['/dashboard']);
});
});
});

这一切都给了我以下错误:

zone.js:569 Unhandled Promise rejection: Cannot match any routes. URL Segment: 'dashboard'

因此,从那里我考虑使用 withRoutes 添加路线。我不喜欢我需要包含 DashboardComponent 因为似乎应该有一些可用的模拟/空白组件,特别是因为我不想实际导航和加载另一条路线,但我找不到类似的东西:

TestBed.configureTestingModule({
declarations: [ LoginComponent ],
imports: [
SharedModule,
RouterTestingModule.withRoutes([{
path: 'dashboard',
component: DashboardComponent
}])
],
...
})
.compileComponents();

但这只会给我一个新错误:

Component DashboardComponent is not part of any NgModule or the module has not been imported into your module.

所以我想也许我需要声明DashboardComponent,所以我将它添加到声明数组中:

TestBed.configureTestingModule({
declarations: [ LoginComponent, DashboardComponent ],
..
})
.compileComponents();

但这只会导致另一个错误:

Unhandled Promise rejection: Cannot find primary outlet to load 'DashboardComponent'

在这一点上,似乎必须有一种更简单的方法来做到这一点,因为这是一个非常常见的场景,但我已经尝试了其他人所说的他们使用的所有内容,并且所有内容都只会进一步深入这个兔子洞。

最佳答案

事实证明,解决方案非常简单......

只需添加 RouterTestingModule 就差不多了,只需要在所有测试中监视 router.navigate 以防止它们尝试实际导航到另一条路线。

describe('LoginComponent', () => {
let component: any;
let fixture: ComponentFixture<LoginComponent>;

beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ LoginComponent ],
imports: [
SharedModule,
RouterTestingModule // This provides the mock router, location and routerLink
],
providers: [{
provide: AuthService,
useClass: MockAuthService
}, {
provide: JwtService,
useClass: MockJwtService
}, {
provide: StorageService,
useClass: MockStorageService
}],
schemas: [ NO_ERRORS_SCHEMA ]
})
.compileComponents();
}));

beforeEach(() => {
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
fixture.detectChanges();
spyOn(component.router, 'navigate'); // This prevents every test from calling the real router.navigate which means I don't need to add routes to RouterTestingModule
});

describe('login', () => {
it('should call router.navigate with the dashboard route if the login is successful', () => {
spyOn(component.router, 'navigate');
component.authService.login.and.returnValue(Observable.of({ access_token: 'fake_token' }));
component.login(component.loginForm);
expect(component.router.navigate).toHaveBeenCalledWith(['/dashboard']);
});
});
});

关于Angular 2 如何测试使用路由器的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43903954/

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