Angular项目ngx-pagination分页正常但单元测试失败如何解决?
问题原因
首次报错(找不到paginate管道)
Angular 单元测试的 TestBed 运行环境是完全独立的,不会自动继承你业务模块 ListViewPageModule 里导入的依赖。你没有在测试配置中引入 NgxPaginationModule,模板解析时识别不到 paginate 管道,就会抛出 NG0302 错误。
二次报错原因
- 你把自定义管道
ListViewPipe错误放到了 TestBed 的imports数组中:Angular 规定只有 NgModule 类才能放到 imports 数组,管道/组件/指令都需要放到declarations数组中,所以会提示「请添加 @NgModule 注解」。 carGroups未定义:你的 Mock 服务没有正确返回车辆列表数据,或者组件初始化后没有触发数据赋值,执行测试用例时component.carGroups还是空值,调用carGroups[0]就会抛出 undefined 相关错误。
修复方案
按以下步骤修改你的测试类配置:
- 在 TestBed 的 imports 数组中补全所有模板用到的依赖模块
- 在 declarations 数组中添加自定义管道
ListViewPipe - 确保 Mock 服务返回有效数据,必要时主动触发组件初始化逻辑
修改后的测试配置参考:
import { Component, NO_ERRORS_SCHEMA } from '@angular/core'; import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { Router } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { IonicModule } from '@ionic/angular'; import { MockListClientServiceService } from 'src/app/Mock/MockListClientServiceService'; import { ListClientServiceService } from 'src/app/services/list-client-service.service'; // 补全导入缺失的依赖 import { NgxPaginationModule } from 'ngx-pagination'; import { Ng2SearchPipeModule } from 'ng2-search-filter'; import { FormsModule } from '@angular/forms'; import { ListViewPipe } from './list-view.pipe'; import { ListViewPage } from './list-view.page'; describe('ListViewPage', () => { let component: ListViewPage; let fixture: ComponentFixture<ListViewPage>; let router: Router; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ // 声明用到的组件、自定义管道 declarations: [ ListViewPage, MockHeaderComponent, ListViewPipe], schemas: [NO_ERRORS_SCHEMA], // 补全导入依赖模块 imports: [ IonicModule.forRoot(), RouterTestingModule, NgxPaginationModule, Ng2SearchPipeModule, FormsModule ], providers: [ListClientServiceService] }).compileComponents(); TestBed.overrideComponent( ListViewPage, { set: { providers: [ { provide: Router, useClass: class { navigate = jasmine.createSpy('detail-view'); } }, { provide: ListClientServiceService, useClass: MockListClientServiceService } ] } } ); fixture = TestBed.createComponent(ListViewPage); router = fixture.debugElement.injector.get(Router); component = fixture.componentInstance; // 主动触发初始化,确保Mock数据赋值到carGroups component.ngOnInit(); fixture.detectChanges(); })); it('should create', () => { expect(component).toBeTruthy(); }); it('should open Details', async (done) => { // 先判断carGroups有值再执行逻辑 expect(component.carGroups?.length).toBeGreaterThan(0); component.openCarGroup(component.carGroups[0].id); expect(router.navigate).toHaveBeenCalledWith(['/detail-view', { carGroupId: component.carGroups[0].id }]); done(); }); }); @Component({ selector: 'app-header', template: '' }) class MockHeaderComponent { }
内容的提问来源于stack exchange,提问作者Doncarlito87
相关产品推荐
相关产品推荐

