You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular项目ngx-pagination分页正常但单元测试失败如何解决?

问题原因

首次报错(找不到paginate管道)

Angular 单元测试的 TestBed 运行环境是完全独立的,不会自动继承你业务模块 ListViewPageModule 里导入的依赖。你没有在测试配置中引入 NgxPaginationModule,模板解析时识别不到 paginate 管道,就会抛出 NG0302 错误。

二次报错原因

  1. 你把自定义管道 ListViewPipe 错误放到了 TestBed 的 imports 数组中:Angular 规定只有 NgModule 类才能放到 imports 数组,管道/组件/指令都需要放到 declarations 数组中,所以会提示「请添加 @NgModule 注解」。
  2. carGroups 未定义:你的 Mock 服务没有正确返回车辆列表数据,或者组件初始化后没有触发数据赋值,执行测试用例时 component.carGroups 还是空值,调用 carGroups[0] 就会抛出 undefined 相关错误。

修复方案

按以下步骤修改你的测试类配置:

  1. 在 TestBed 的 imports 数组中补全所有模板用到的依赖模块
  2. 在 declarations 数组中添加自定义管道 ListViewPipe
  3. 确保 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 12:45:02