我對角度測驗真的很陌生,而且我找不到解決這個問題的方法。我試圖對單擊錨標記后呼叫的方法進行測驗。這個錨標記位于一個 ng-container 中,它屬于 ng-switch 的 case:
<ng-container [ngSwitch]="layout">
<ng-container *ngSwitchCase="'public'" >
<div navbar-toggler"
type="button"
data-toggle="collapse"
data-target="#navbarText"
>
</button>
</div>
<div >
<ul >
<ng-container *ngFor="let link of object">
<li >
<a
(click)="navigateToURL(link.route)"
>
{{ string }}
</a>
</li>
</ng-container>
</ul>
</div>
</ng-container>
<ng-container *ngSwitchCase="'other'">
<div >
<ul >
<ng-container *ngFor="let link of otherObject">
<li >
<a id='one'
(click)="navigateToURL(link.route)"
>
{{ other string }}
</a>
</li>
</ng-container>
</ul>
</div>
</ng-container>
</ng-container>
該方法將是某種路由器重定向
navigateToURL(url:stringstring):void{
this.router.navigateByURL(url)
}
然后在我的測驗中
describe('AppComponent [navigation-root]', () => {
let fixture: ComponentFixture<AppComponent>;
let component: AppComponent;
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [AppComponent],
providers: [
{
provide: Router,
useValue: routerMock,
},
],
schemas: [NO_ERRORS_SCHEMA],
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
})
})
);
test('Should create the navigation micro app', () => {
expect(component).toBeTruthy();
});
describe('When user is redirected from anchor tag click', () => {
test('Should call navigateToURL method from anchor tag on click ', () => {
const goToRouteSpy = jest.spyOn(component, 'navigateToURL');
const link = fixture.debugElement.nativeElement.querySelector('[id="one"]') as HTMLElement;
link.click();
fixture.detectChanges();
expect......
});
});
});
但是由于無法單擊 null ,測驗失敗并引發錯誤有人可以幫我解決這個問題嗎?非常感謝你
uj5u.com熱心網友回復:
您必須先模擬資料,然后才能對其進行測驗。
test('Should call navigateToURL method from anchor tag on click ', () => {
const goToRouteSpy = jest.spyOn(component, 'navigateToURL');
// first mock layout to be other
component.layout = 'other';
// mock the array of otherObject
component.otherObject = [{ route: 'abc' }];
// call fixture.detectChanges() so the HTML is updated with the previous
// properties
fixture.detectChanges();
// hopefully should work now, by the way it is better if you do
// .querySelector('#one') instead of '[id="one"]'
const link = fixture.debugElement.nativeElement.querySelector('[id="one"]') as HTMLElement;
link.click();
fixture.detectChanges();
expect......
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/411668.html
標籤:
