我要用方法测试组件:
switchDocumentLanguage(lang, formData):any {
if (lang === this.currentLang) {
return null;
}
if (formData.invalid && this.currentLang === this.appConfig.defaultLanguage ||
!this.documentFormData.content && this.currentLang === this.appConfig.defaultLanguage) {
return this.modalService.open(this.setDefaultModal);
}
//(2*)
if (formData.invalid || !this.documentFormData['content']) {
return this.modalService.open(this.tabSwitchModal).result.then(() => {
this.fillFormData(lang);
}, (reason) => {
});
} else {
return this.fillFormData(lang);
}
}它处于标记为(2*)的状态。
在测试中,我使用存根类ModalService:
class ModalService {
open(someArg?: any){
return {result : Promise.resolve('success')};
}
}
const appConfig =
{
defaultLanguage: 'en-US'
}我的测试配置看起来如下:
describe('document.edit component test', () => {
let component: DocumentEditComponent;
let fixture: ComponentFixture<DocumentEditComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [FormsModule],
schemas: [NO_ERRORS_SCHEMA],
declarations: [DocumentEditComponent],
providers: [{provide: AppConfig, useValue: appConfig},
{provide: DocumentsService, useValue: documentsService},
{provide: NgbModal, useClass: ModalService},
{provide: ActivatedRoute, useValue: activatedRoute},
{provide: BaThemeSpinner, useValue: loader},
{provide: PopupResultService, useValue: popupResultService},
],
})
});
beforeEach(() => {
fixture = TestBed.createComponent(DocumentEditComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});下面是给我带来错误的测试:
it("try to leave custom language with invalid form", async(() => {
const componentService = fixture.debugElement.injector.get(NgbModal);
let spyObj = spyOn(componentService, "open")
component.documentFormData.content = "some test values";
component.currentLang = "es-VE";
fixture.detectChanges();
component.switchDocumentLanguage("ru-Ru", {invalid: true})
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(spyObj).toHaveBeenCalled()
})
}));错误文本:
document.edit component test try to leave custom language with invalid form
Failed: Cannot read property 'result' of undefined
TypeError: Cannot read property 'result' of undefined看起来我的存根类"ModalService“不返回任何东西,我试着将console.log()放在那里,但它从未出现。有没有人遇到过类似的情况?
发布于 2018-08-15 13:25:53
不是因为你有间谍才叫它的。
也许你能做的就是用callThrough()扩展间谍
let spyObj = spyOn(componentService, "open").and.callThrough();编辑:
您也可以使用returnValue()完成它。
let spyObj = spyOn(componentService, "open").and.returnValue({result : Promise.resolve('success')}); 在本例中,将不会调用open(),相反,您将返回由模拟类方法返回的相同结果。如果使用这个,您也不需要模拟类。
https://stackoverflow.com/questions/51858418
复制相似问题