我正在对使用其他两个组件的组件进行单元测试。单击按钮会创建其他组件
.html
<div id="homepage-top-div" class="homepage-component-css-grid-container"> ...
<button id="get-question-list-button" [routerLink]="questionListRouterLink" class="btn content-div__button--blue css-grid-item-button-div btn-sm">See Questions</button>
</div>
<div id="practice-component-top-div" class="css-grid-container-div common-styles-div--white"> <!-- 4 rows, 1 column-->
...
<button id="new-question-button" [routerLink]="newQuestionRouterLink" class="btn content-div__button--blue css-grid-item-button-div btn-sm">Create a Question</button>
</div>
</div>
.ts
export class HomepageContentComponentComponent implements OnInit {
public questionListRouterLink="/practice-question-list";
public newQuestionRouterLink="/new-practice-question";
constructor() {
}
ngOnInit() {
}
}
我创建了一个spec
,但是运行它时出现以下错误-Failed: Unexpected directive 'NewPracticeQuestionComponent' imported by the module 'DynamicTestModule'. Please add a @NgModule annotation.
规范是
import {async, ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing';
import { HomepageContentComponentComponent } from './homepage-content-component.component';
import {RouterTestingModule} from "@angular/router/testing";
import {AppRoutingModule} from "../app-routing.module";
import {Router} from "@angular/router";
import {routes} from '../app-routing.module';
import {NewPracticeQuestionComponent} from "../new-practice-question/new-practice-question.component";
import {PraticeQuestionListComponent} from "../pratice-question-list/pratice-question-list.component";
import {NgModule} from "@angular/core";
import {AppModule} from "../app.module";
fdescribe('HomepageContentComponentComponent', () => {
let component: HomepageContentComponentComponent;
let fixture: ComponentFixture<HomepageContentComponentComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports:[
AppModule,
AppRoutingModule,
RouterTestingModule.withRoutes(routes),
NewPracticeQuestionComponent,
PraticeQuestionListComponent
],
declarations: [ HomepageContentComponentComponent,
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(HomepageContentComponentComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should navigate to New Questions Component when New Question button is clicked',fakeAsync(()=>{
let router:Router;
let location:Location;
router = TestBed.get(Router);
location = TestBed.get(Location);
console.log('initial router is ',router);
console.log('initial location is ',location);
router.initialNavigation();
router.navigate(['new-practice-question']);
tick();
console.log('new router is ',router);
console.log('new location is ',location);
expect(location.pathname).toBe('/new-practice-question');
}));
});
答案 0 :(得分:1)
问题在于NewQuestionComponent
和PracticeListComponent
应该在declarations
中,而不是imports