![](/img/trans.png)
[英]How to capture nativeElement for <ng-template> used in ngx-modal in Jasmine Unit test
[英]How can I test a modal's elements with ng-template and the action that triggers it?
我閱讀了Angular Testing ,我不確定是否有任何關於模態內測試元素以及如何檢查自定義操作的參考。 我的目的是編寫必要的測試以確保我的函數和模式按預期工作。
由於模態被隱藏,檢查模態元素是否出現的測試失敗。 所以我想這里缺少一些東西。
這是我的photos.components.ts
文件:
import {Component, OnInit, ViewEncapsulation} from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'app-photos',
templateUrl: './photos.component.html',
styleUrls: ['./photos.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class PhotosComponent implements OnInit {
constructor(private modalService: NgbModal) { }
openDarkModal(content) {
this.modalService.open(content, { windowClass: 'dark-modal', size: 'lg', centered: true });
}
ngOnInit() {
}
}
這是我的photos.component.html
文件:
<div>
<div class="col-lg-4 col-sm-6 mb-3">
<a><img (click)="openDarkModal(content)" id="photo-one" class="img-fluid z-depth-4 relative waves-light" src="#" alt="Image" data-toggle="content" data-target="#content"></a>
</div>
</div>
<!-- Dark Modal -->
<ng-template #content let-modal id="ng-modal">
<div class="modal-header dark-modal">
<img (click)="modal.dismiss('Cross click')" id="modal-image" class="embed-responsive-item img-fluid" src="#" alt="Image" allowfullscreen>
</div>
<div class="justify-content-center flex-column flex-md-row list-inline">
<ul class="list-inline flex-center text-align-center text-decoration-none" id="modal-buttons-list">
<li><a style="color: white;" href="#"><button mdbBtn type="button" size="sm" class="waves-light" color="indigo" mdbWavesEffect><i class="fab fa-facebook-f"></i></button></a></li>
<li><a style="color: white;" href="#"><button mdbBtn type="button" size="sm" class="waves-light" color="cyan" mdbWavesEffect><i class="fab fa-twitter"></i></button></a></li>
<li><a style="color: white;" href="#"><button mdbBtn type="button" size="sm" class="waves-light btn btn-blue-grey" mdbWavesEffect><i class="fas fa-envelope"></i></button></a></li>
</ul>
</div>
</ng-template>
這就是我處理photos.component.spec.ts
文件的地方:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { PhotosComponent } from './photos.component';
import { NO_ERRORS_SCHEMA } from '@angular/core';
describe('PhotosComponent', () => {
let component: PhotosComponent;
let fixture: ComponentFixture<PhotosComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ PhotosComponent ],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(PhotosComponent);
component = fixture.componentInstance;
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should render the first photo', () => {
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('#photo-one')).toBeTruthy();
});
});
我需要Dark Modal內部元素的測試用例和openDarkModal的測試。 除了代碼外,如果有適合初學者的 Angular 7 測試參考,我們將不勝感激。
讓我幫你解決這個問題。 可以說你有
應用程序組件.html
<div id="title">
{{title}}
</div>
<ng-template #content
let-modal
id="ng-modal">
<div class="modal-header dark-modal">
Header
</div>
<div class="justify-content-center flex-column flex-md-row list-inline">
Body
</div>
</ng-template>
應用程序組件.ts
import { Component, ViewChild, TemplateRef } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
title = 'AngularProj';
@ViewChild('content') modalRef: TemplateRef<any>;
}
您需要以稍微不同的方式編寫spec
文件:
app.component.spec.ts
import { TestBed, async, ComponentFixture } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { ViewChild, Component, OnInit, AfterContentInit, TemplateRef } from '@angular/core';
import { By } from '@angular/platform-browser';
@Component({
template: `
<ng-container *ngTemplateOutlet="modal"> </ng-container>
<app-root></app-root>
`,
})
class WrapperComponent implements AfterContentInit {
@ViewChild(AppComponent) appComponentRef: AppComponent;
modal: TemplateRef<any>;
ngAfterContentInit() {
this.modal = this.appComponentRef.modalRef;
}
}
describe('AppComponent', () => {
let app: AppComponent;
let fixture: ComponentFixture<WrapperComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [WrapperComponent, AppComponent],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(WrapperComponent);
const wrapperComponent = fixture.debugElement.componentInstance;
app = wrapperComponent.appComponentRef;
fixture.detectChanges();
});
it('should create the app', async(() => {
expect(app).toBeDefined();
}));
it('should have title in HtmL ', () => {
const titleText = (fixture.debugElement.nativeElement.querySelector('#title').innerText);
expect(titleText).toBe('AngularProj');
});
it('should have Header in HtmL ', () => {
const headerText = (fixture.debugElement.queryAll(By.css('.modal-header.dark-modal'))[0].nativeElement.innerText);
expect(headerText).toBe('Header');
});
});
WrapperComponent
) 包裝了app-root
。app-root
有ng-template
,所以它不會自己渲染。 這會造成一個棘手的情況,因為我們需要渲染app.component
的這一部分。@ViewChild('content') modalRef: TemplateRef<any>;
公開ng-template
然后使用它在WrapperComponent
內渲染。我知道這看起來像是 hack,但在我閱讀的所有文章中,這就是我們實現這一目標的方式。
用於測試類似的東西:
openDarkModal(content) {
this.modalService.open(content, { windowClass: 'dark-modal', size: 'lg', centered: true });
}
您可以使用spy
,但在此之前將modalService
公開以便可以對其進行監視:
constructor(public modalService: NgbModal) { }
您還可以使用jasmine.createSpyObj
並將服務private
。
然后在spec
中:
import { NgbModalModule } from '@ng-bootstrap/ng-bootstrap';
TestBed.configureTestingModule({
imports: [NgbModalModule],
declarations: [PhotosComponent, /*WrapperComponent*/],
schemas: [NO_ERRORS_SCHEMA],
})
// and in it block
it('should call modal Service open function when clicked ', async(() => {
spyOn(component.modalService,'open').and.callThrough();
const openModalEle= fixture.debugElement.nativeElement.querySelector('#photo-one'));
openModalEle.click();
expect(component.modalService.open).toHaveBeenCalled();
}));
使用 Angular 11,您需要進行一些更改:
@Component({
template: `
<div>
<ng-container *ngTemplateOutlet="modal"> </ng-container>
</div>
<app-root> </app-root>
`,
})
class WrapperComponent implements AfterViewInit {
@ViewChild(AppComponent) appComponentRef: AppComponent;
modal: TemplateRef<any>;
constructor(private cdr: ChangeDetectorRef) {}
ngAfterViewInit() {
this.modal = this.appComponentRef.modalRef;
this.cdr.detectChanges();
}
}
describe('AppComponent', () => {
let fixture: ComponentFixture<WrapperComponent>;
let wrapperComponent: WrapperComponent;
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [WrapperComponent, AppComponent],
imports: [ModalModule.forRoot()],
}).compileComponents();
})
);
beforeEach(() => {
fixture = TestBed.createComponent(WrapperComponent);
wrapperComponent = fixture.debugElement.componentInstance;
fixture.detectChanges();
});
it('should create the app', () => {
expect(wrapperComponent).toBeDefined();
expect(wrapperComponent.appComponentRef).toBeDefined();
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.