所以我正在做一些单元测试。我尝试对以下组件进行单元测试:
export class EcheqDisplayComponent implements OnInit {
echeq: EcheqSubmissionApi;
orgId = 1;
constructor(
private route: ActivatedRoute
) {
this.echeq = this.route.snapshot.data['submission'];
}
ngOnInit() {
}
getAnswers(page: EcheqPageApi): any[] {
return page.elements.map(element => this.echeq.answers[element.name]);
}
这是它的单元测试:
describe('EcheqDisplayComponent', () => {
let component: EcheqDisplayComponent;
let fixture: ComponentFixture<EcheqDisplayComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ],
imports:[ParticipantEcheqModule,
RouterModule.forRoot([])
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(EcheqDisplayComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
fit('should create component', () => {
expect(component).toBeTruthy();
});
});
所以我不会出错。
但是我的问题是。这是做ti的正确方法吗?
因为对ActivatedRoute使用模拟不是更好吗?
如果是的话,那怎么做才正确呢?
谢谢
这是它的模板:
<div class="echeq-display" *ngIf="echeq">
<header class="echeq-display-header header">
<div class="echeq-display-info">
<h1 class="heading echeq-display-heading">
{{ echeq.definition.title }}
</h1>
<div class="sub-heading echeq-display-subheading">
<span class="echeq-display-creator">
Toegekend door:
{{ echeq.assignedByProfName ? echeq.assignedByProfName : 'Het Systeem' }}
</span>
<span class="echeq-display-date">{{
echeq.definition.createdOnUtc | date: 'dd MMM'
}}</span>
</div>
</div>
<app-meta-box
[metadata]="{
numPages: echeq.definition.numPages,
vPoints: echeq.definition.awardedVPoints
}"
></app-meta-box>
</header>
<main class="echeq-display-questions body">
<app-echeq-question
*ngFor="let page of echeq.definition.pages; let i = index"
[page]="page"
[readonly]="true"
[number]="i + 1"
[answers]="getAnswers(page)"
></app-echeq-question>
</main>
</div>
和这样的单元测试:
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ],
providers: [
{ provide: ActivatedRoute, useClass: MockActivatedRoute }
],
imports:[
ParticipantEcheqModule
]
})
.compileComponents();
}));
这是app-meta-box组件:
export class MetaData {
numPages: number;
vPoints: number;
}
@Component({
selector: 'app-meta-box',
templateUrl: './meta-box.component.html',
styleUrls: ['./meta-box.component.scss']
})
export class MetaBoxComponent implements OnInit {
@Input() metadata: MetaData;
constructor() {}
ngOnInit() {}
}
答案 0 :(得分:0)
调用“ TestBed.configureTestingModule({...})”来配置测试模块时,您只需在“ providers”属性中为模拟的ActivatedRoute对象提供必要的变量即可。
class MockActivatedRoute {
public snapshot = {
data: {
submission: {
answers: {}
}
}
};
}
TestBed.configureTestingModule({
declarations: [ ],
providers: [
{ provide: ActivatedRoute, useClass: MockActivatedRoute }
]
imports:[
ParticipantEcheqModule,
// RouterModule.forRoot([]) // Not required after mocking the "ActivatedRoute"
]
})
.compileComponents();
通过这种方法,您可以在ActivatedRoute中测试组件的不同值。