用茉莉花测试btn点击,得到"Cannot read properties of null (reading 'click')"



我正在测试两次按钮点击的功能,以及是否会因此打开模态。

我已经在Jasmine中测试了这些点击的几种变体,我不确定如何确定这个错误的原因,或者如何减轻它:

TypeError: Cannot read properties of null (reading 'click')

组件规格

describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
fit('can promote', () => {
// ARRANGE
// spyOn(component, 'doPromoteMethod'); // no changes if uncommented
const dialog = TestBed.inject(MatDialog) as jasmine.SpyObj<MatDialog>;
const dialogRef = TestBed.inject(MatDialogRef) as jasmine.SpyObj<MatDialogRef<any>>;
dialog.open.and.returnValue(dialogRef);
dialogRef.afterClosed.and.returnValue(of());
queryParams$.next({});
// ACT
// 1st click evt: Ellipsis menu click (opens dropdown) //
const ellipsisBtn: HTMLButtonElement = fixture.nativeElement.parentNode.querySelector('[data-atm="actions"]');
ellipsisBtn.click();
fixture.detectChanges();
// 2nd click evt: Btn click //
const promoteBtn: HTMLButtonElement = fixture.nativeElement.parentNode.querySelector('[data-atm="promote"]');
promoteBtn.click();
fixture.detectChanges();
fixture.whenStable();
// ASSERT
expect(dialog.open).toHaveBeenCalled;
});
});

组件.html

<ng-container matColumnDef="action">
<th mat-header-cell *matHeaderCellDef=""></th>
<td mat-cell *matCellDef="let promotion">
<button mat-icon-button
class="ellipsis-btn"
data-atm="actions"
[matMenuTriggerFor]="menu"
[matMenuTriggerData]="{ 'promotion': promotion }"
role="menubar">
<img src="/assets/icon/ellipsis-menu.svg" />
</button>
</td>
</ng-container>
<mat-menu class="promotion-menu" #menu="matMenu">
<ng-template matMenuContent let-promotion="promotion">
<div class="promotion-menu">
<button *ngIf="shouldAllowPromotion(promotion)" mat-menu-item data-atm="promote" (click)="doPromoteMethod(promotion)">Do promotion</button>
</div>
</ng-template>
</mat-menu>

我看不出你在任何地方嘲笑shouldAllowPromotion。该方法很可能返回falsy,因此没有呈现您需要的按钮。

相关内容

最新更新