typescript - Angular - 如何使用 Jest 和 NgMocks 模拟包装组件
在我们的项目中,我们可以为应用程序中的多个元素分配用户角色,当缺少所需角色时会禁用这些元素。但由于某些按钮会应用其他条件,即使角色检查通过,这些条件也可能会禁用组件,因此我们的组件也会接管并在必要时禁用其子组件。设计这一点的原因是,如果元素应该被禁用,我们可以轻松显示工具提示。
// app-role-element
<div matTooltip="{{ tooltipMessage | translate }}" [matTooltipDisabled]="!isDisabled">
<ng-content> </ng-content>
</div>
// .ts
export class AppRoleElement implements AfterConentInit {
@Input('roles') roles: string[];
@ContentChild('roleElement') roleElement: MatButton;
constructor(...){}
ngAfterContentInit(): void {
...
this.setDisabled();
}
setDisabled(): void {
if (this.roleElement) {
if (this.isDisabled) {
this.roleElement.disabled = true; // disable if no role
} else {
this.roleElement.disabled = this.disableCondition; // disable if other condition
}
}
}
}
// usage
<app-role-component
[role]="['required-role']"
[disableCondition]= "isRunning || isUnstable"
[id]="startButtonRoleElem"
>
<button mat-raised-button id="startBtnId" (click)="start()">Start</button>
</app-role-component>
这种方法可以使用,但很难进行单元测试。在上面的代码中,如果我要编写一个单元测试,点击“开始”按钮,通过 ID 选择它会绕过角色元素并调用远程服务,即使不应该这样。通过 ID 选择角色元素不会将点击事件传播到按钮上。
test('to prevent click on a start btn when form is invalid', () => {
spectator.component.runEnabled$ = of(false);
spectator.detectComponentChanges();
const checkExportFolderSpy = jest.spyOn(spectator.component, 'checkExportFolder');
spectator.inject(PreferencesService).validateCurrentExportPath.andReturn(of(VALIDATION_RESULT_OK));
spectator.detectChanges();
spectator.click('#startBtnId');
spectator.detectChanges();
expect(checkExportFolderSpy).not.toHaveBeenCalled();
expect(dispatchSpy).not.toHaveBeenCalled();
});
我们正在将 JEST 与 Spectator 和 NgMocks 一起使用,我希望能够利用这些功能来模拟这个组件,但我完全不知道该怎么做。而且我也不太确定应该在多大程度上模拟它,是应该将点击事件传递给子组件,还是禁用子组件?有没有任何想法或建议来处理这个问题?
答案#1
你的案子很复杂。
这很复杂,因为:
- 该按钮通过
MatButton被禁用,因此无法被模拟 - 因为我们想测试
AppRoleElement,它也不能被模拟 triggerEventHandler不会尊重disabled属性,并且总是触发点击事件
因此在测试中我们需要:
- 保持
AppRoleElement和MatButton原样 - 为残障人士和非残障人士创造一个特殊环境
- 通过
nativeElement点击按钮
下面的代码仅使用了 ng-mocks,角色检测已被简化。
import {AfterContentInit, Component, ContentChild, Input, NgModule,} from '@angular/core';
import {MatButton, MatButtonModule} from '@angular/material/button';
import {MockBuilder, MockRender, ngMocks} from 'ng-mocks';
@Component({
selector: 'app-role-component',
template: `
<div>
<ng-content></ng-content>
</div>
`,
})
class AppRoleElement implements AfterContentInit {
@Input() public disable: boolean | null = null;
@ContentChild(MatButton) public roleElement?: MatButton;
public ngAfterContentInit(): void {
this.setDisabled();
}
public setDisabled(): void {
if (this.roleElement) {
this.roleElement.disabled = this.disable;
}
}
}
@NgModule({
declarations: [AppRoleElement],
imports: [MatButtonModule],
})
class AppModule {}
fdescribe('ng-mocks-click', () => {
// Keeping AppRoleElement and MatButton
beforeEach(() => MockBuilder(AppRoleElement, AppModule).keep(MatButton));
it('is not able to click the disabled button', () => {
// specific params for the render
const params = {
disabled: true,
start: jasmine.createSpy('start'),
};
// rendering custom template
MockRender(
`
<app-role-component
[disable]="disabled"
>
<button mat-raised-button id="startBtnId" (click)="start()">Start</button>
</app-role-component>
`,
params,
);
// click on a disable element isn't propagandized
ngMocks.find('button').nativeElement.click();
// asserting
expect(params.start).not.toHaveBeenCalled();
});
// checking the enabled case
it('is able to click the button', () => {
const params = {
disabled: false,
start: jasmine.createSpy('start'),
};
MockRender(
`
<app-role-component
[disable]="disabled"
>
<button mat-raised-button id="startBtnId" (click)="start()">Start</button>
</app-role-component>
`,
params,
);
ngMocks.find('button').nativeElement.click();
expect(params.start).toHaveBeenCalled();
});
});
