我有一个问题,当我写角度的事实,我想测试按钮的路由,但它有这样的错误
这是我的homepage.component.spec.ts文件(这不是app.component.spec.ts文件)
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { DebugElement } from '@angular/core';
import { HomepageComponent } from './homepage.component';
import { Router } from '@angular/router';
import { inject } from '@angular/core/src/render3';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from '../app.component';
import { RegisterpageComponent } from'../registerpage/registerpage.component';
import { Location } from '@angular/common';
describe('HomepageComponent', () => {
let component: HomepageComponent;
let fixture: ComponentFixture<HomepageComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [RouterTestingModule],
declarations: [ HomepageComponent,
AppComponent,
RegisterpageComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(HomepageComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
// tslint:disable-next-line:prefer-const
let location: Location;
// tslint:disable-next-line:prefer-const
let router: Router;
// tslint:disable-next-line:prefer-const
router = TestBed.get(Router);
location = TestBed.get(Location);
router.initialNavigation();
it('navigate to "registerpage"', () => {
router.navigate(['register']);
expect(location.path()).toBe('/register');
});
});
这是app-routing.module.ts文件
import { ApplicationRef, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Routes, RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { HomepageComponent } from './homepage/homepage.component';
import { RegisterpageComponent } from './registerpage/registerpage.component';
const routes: Routes = [
{ path: '',
// redirectTo: '/home',
component: HomepageComponent,
pathMatch: 'full' },
{ path: 'register',
component: RegisterpageComponent}
// { path: '**',
// component: PagenotfoundComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule { }
我坚持了一个星期,似乎没有希望请帮助我!感谢
ps.actually我很困惑,我必须在AppComponent.spec.ts文件中编写测试代码
答案 0 :(得分:0)
我只是遇到了同样的问题,并且在寻找答案时遇到了这个问题。
以下几行应移至beforeEach。
router = TestBed.get(Router);
location = TestBed.get(Location);
router.initialNavigation();
完整。...
let location: Location;
let router: Router;
beforeEach(() => {
fixture = TestBed.createComponent(HomepageComponent);
component = fixture.componentInstance;
fixture.detectChanges();
router = TestBed.get(Router);
location = TestBed.get(Location);
router.initialNavigation();
});