ag-Grid的ICellRendererAngularComp自定义渲染器如何单元测试
解决方法
1. 核心思路
你只需要在mock的params参数里新增clicked属性,用测试框架的Spy函数模拟即可,不需要额外导入ag-grid的预定义类或模块,单元测试阶段只需要覆盖组件自身逻辑即可。
2. 调整测试代码
修改beforeEach中的params定义
给params补充clicked的Spy模拟函数,同时把params提到describe作用域下方便测试用例访问:
// 在describe作用域下声明mockParams变量 let mockParams: any; beforeEach(() => { fixture = TestBed.createComponent(GridButtonsComponent); component = fixture.componentInstance; // 定义mock参数 mockParams = { column: 'status', value: 'test-value', data: { actionType: '' }, // 新增clicked的spy模拟 clicked: jasmine.createSpy('clicked') }; component.agInit(mockParams); fixture.detectChanges(); });
调整最后一条测试用例
补充对clicked方法调用的断言:
it('should set correct actionType and trigger clicked callback', () => { const testAction = 'edit'; component.triggerAction(testAction); // 验证actionType设置正确 expect(component.params.data.actionType).toBe(testAction); // 验证clicked方法被调用,且参数符合预期 expect(mockParams.clicked).toHaveBeenCalledOnceWith(mockParams.data); });
3. 完整修改后的测试代码
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { GridButtonsComponent } from './grid-buttons.component'; describe('GridButtonsComponent', () => { let component: GridButtonsComponent; let fixture: ComponentFixture<GridButtonsComponent>; let mockParams: any; beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [GridButtonsComponent] }).compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(GridButtonsComponent); component = fixture.componentInstance; mockParams = { column: 'status', value: 'test-value', data: { actionType: '' }, clicked: jasmine.createSpy('clicked') }; component.agInit(mockParams); fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should return false for refresh', () => { expect(component.refresh()).toBe(false); }); it('should set correct actionType and trigger clicked callback', () => { const testAction = 'edit'; component.triggerAction(testAction); expect(component.params.data.actionType).toBe(testAction); expect(mockParams.clicked).toHaveBeenCalledOnceWith(mockParams.data); }); });
如果你使用的测试框架是Jest,只需要把jasmine.createSpy('clicked')换成jest.fn()即可,其余逻辑完全一致。
内容的提问来源于stack exchange,提问作者Akhil RJ
相关产品推荐
相关产品推荐

