花费时间与角度1后开始角度为2.没有单元测试这么多's more of a side project thing, I' m尝试至少开始OK ...我开始使用AngularClass中的示例,如果这有所不同 .
在 app.component.ts
中苦苦挣扎,其中包含我的导航位 . 这里模板的相关位:
<nav class="navbar navbar-light bg-faded">
<div class="container">
<div class="nav navbar-nav">
<a class="navbar-brand" [routerLink]=" ['./'] ">Navbar</a>
<loading class="nav-item nav-link pull-xs-right" [visible]="user === null"></loading>
</div>
</div>
</nav>
<div class="container">
<main>
<router-outlet></router-outlet>
</main>
</div>
<footer>
<hr>
<div class="container">
</div>
</footer>
组件本身并不多:
import { Component, ViewEncapsulation } from '@angular/core';
import { AuthService } from './_services';
import { User } from './_models';
import { Loading } from './_components';
@Component({
selector: 'app',
encapsulation: ViewEncapsulation.None,
template: require('./app.component.html'),
styles: [
require('./app.style.css')
]
})
export class App {
user: User;
constructor(private auth: AuthService) {
}
ngOnInit() {
this.auth.getUser().subscribe(user => this.user = user);
}
}
所有模块,组件和路由都通过App模块引导 . 如果需要可以发布 .
我必须为它编写的测试让我基本上连接了路由器的所有内容(所以看起来如此) . 首先, [routerLink] is not a native attribute of 'a'
. 好的,我解决了 . 然后:
Error in ./App class App - inline template:3:6 caused by: No provider for Router!
所以,我连接路由器,只发现:
Error in ./App class App - inline template:3:6 caused by: No provider for ActivatedRoute!
我添加了,以找出:
Error in ./App class App - inline template:3:6 caused by: No provider for LocationStrategy!
到目前为止,测试看起来像:
import { inject, TestBed, async } from '@angular/core/testing';
import { AuthService } from './_services';
import { Router, RouterModule, ActivatedRoute } from '@angular/router';
import { AppModule } from './app.module';
// Load the implementations that should be tested
import { App } from './app.component';
import { Loading } from './_components';
describe('App', () => {
// provide our implementations or mocks to the dependency injector
beforeEach(() => TestBed.configureTestingModule({
declarations: [App, Loading],
imports: [RouterModule],
providers: [
{
provide: Router,
useClass: class {
navigate = jasmine.createSpy("navigate");
}
}, {
provide: AuthService,
useClass: class {
getAccount = jasmine.createSpy("getAccount");
isLoggedIn = jasmine.createSpy("isLoggedIn");
}
}, {
provide: ActivatedRoute,
useClass: class { }
}
]
}));
it('should exist', async(() => {
TestBed.compileComponents().then(() => {
const fixture = TestBed.createComponent(App);
// Access the dependency injected component instance
const controller = fixture.componentInstance;
expect(!!controller).toBe(true);
});
}));
});
我已经嘲笑输入了,这对我来说似乎不对 . 我错过了什么吗?是否有更智能的方法在测试中加载整个应用程序,而不是一直在每个依赖项中使用?
1 回答
对于测试,您应该使用RouterTestingModule而不是
RouterModule
. 如果你想添加路线,你可以使用withRoutes
See Also
Angular 2 unit testing components with routerLink
Second half of this post想要嘲笑
ActivatedRoute
. 有时您在单元测试时不需要整个路由设施 . 你可以模仿路线 .