在花费时间与角度 1 之后从角度 2 开始。没有进行如此多的单元测试,因为它更像是一个附带项目的东西,我正在尝试至少开始好...我从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);
});
}));
});
我已经在嘲笑输入,这对我来说似乎是错误的。我错过了什么吗?有没有一种更聪明的方法可以在测试中加载整个应用程序,而不是一直插入每个依赖项?