如何在Angular Jest中Mock PrimeNg MenuItem command事件并覆盖测试
要覆盖这些MenuItem的command回调代码,无需模拟PrimeNg菜单的点击交互,直接调用command函数即可,以下是具体步骤和测试用例:
1. 初始化测试环境
先在测试文件中准备组件实例,mock必要依赖,设置selectedGridMenuItem的属性值:
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { YourComponent } from './your.component'; import { SharedService } from '../services/shared.service'; describe('YourComponent', () => { let component: YourComponent; let fixture: ComponentFixture<YourComponent>; let sharedService: jest.Mocked<SharedService>; beforeEach(async () => { const sharedServiceMock = { isMspUser: jest.fn().mockReturnValue(false) }; await TestBed.configureTestingModule({ declarations: [YourComponent], providers: [ { provide: SharedService, useValue: sharedServiceMock } ] }).compileComponents(); fixture = TestBed.createComponent(YourComponent); component = fixture.componentInstance; sharedService = TestBed.inject(SharedService) as jest.Mocked<SharedService>; // 给selectedGridMenuItem赋值,确保回调能获取到参数 component.selectedGridMenuItem = { reqTpsReferenceId: 'test-ref-id', submissionId: 'test-submit-id' }; fixture.detectChanges(); // 触发组件初始化,生成itemsWithdraw数组 });
2. 测试「Withdraw Applicant」的Command
直接调用该MenuItem的command函数,验证对应组件方法是否执行:
it('should call viewApplicantWithdraw when "Withdraw Applicant" command runs', () => { // 监听目标方法 const viewSpy = jest.spyOn(component, 'viewApplicantWithdraw'); // 找到对应的菜单项 const withdrawItem = component.itemsWithdraw.find(item => item.label === 'Withdraw Applicant'); // 调用command函数(PrimeNg会传event参数,这里传空对象即可) withdrawItem.command({}); // 验证方法被正确调用 expect(viewSpy).toHaveBeenCalledWith('test-ref-id'); });
3. 测试「History」的Command
同理测试History项的command逻辑:
it('should call getRequisitionSubmissionStatusHistoryById when "History" command runs', () => { const historySpy = jest.spyOn(component, 'getRequisitionSubmissionStatusHistoryById'); const historyItem = component.itemsWithdraw.find(item => item.label === 'History'); historyItem.command({}); expect(historySpy).toHaveBeenCalledWith('test-submit-id'); });
4. 测试disabled状态(可选)
如果需要覆盖disabled属性的逻辑,可测试不同用户状态下的禁用情况:
it('should disable "Withdraw Applicant" for MSP users', () => { // 修改mock返回值,模拟MSP用户 sharedService.isMspUser.mockReturnValue(true); // 重新初始化菜单项(假设菜单项在ngOnInit中生成) component.ngOnInit(); fixture.detectChanges(); const withdrawItem = component.itemsWithdraw.find(item => item.label === 'Withdraw Applicant'); expect(withdrawItem.disabled).toBe(true); });
执行上述测试后,command: e => this.viewApplicantWithdraw(...)和command: e => this.getRequisitionSubmissionStatusHistoryById(...)这些代码行就会被覆盖率统计到。
内容的提问来源于stack exchange,提问作者Felix
相关产品推荐
相关产品推荐

