【问题标题】:Mock NgbModal in Angular在 Angular 中模拟 NgbModal
【发布时间】:2017-08-30 11:18:36
【问题描述】:
我需要模拟 NgbModal 以进行一些有角度的单元测试,但我不知道该怎么做。这是我的功能:
openModal(deviceID: string, productID: string){
const modalRef = this.modalService.open(ProductModal)
modalRef.componentInstance.content = {
deviceId: deviceID,
productId: productID
}
modalRef.componentInstance.toEmit.subscribe(($e) => {
if ($e === true) this.reloadList();
});
}
我该怎么办?
【问题讨论】:
标签:
angular
unit-testing
jasmine
ng-bootstrap
ng-modal
【解决方案1】:
假设您的 modalService 是 NgbModal,您想要测试的逻辑似乎在模态内容 (ProductModal) 内部,而不是 NgbModal 本身。
如您所见,使用.open() 后,您的modalRef.<em>component</em>Instance 将成为ProductModal 的实例;所以你可以测试ProductModal 作为任何 component 与例如组件夹具并完全跳过modalService:
(再次假设ProductModal 是一个带有适当装饰的组件。)
let component: ProductModal;
let fixture: ComponentFixture<ProductModal>;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [ NgbModal, NgbActiveModal ],
declarations: [ ProductModal ]
});
fixture = TestBed.createComponent(ProductModal);
component = fixture.componentInstance;
fixture.detectChanges();
});
// now you have the component in `component`, so you can test
// component.content
// component.toEmit
// …