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

如何为route.queryParamMap编写Angular单元测试?解决未定义报错

解决Angular组件单元测试中ActivatedRoute.queryParamMap的mock问题

问题原因

组件初始化时直接访问this.route.queryParamMap并调用其pipe方法,但当前单元测试中mock的ActivatedRoute仅提供了snapshot和routeConfig,未定义queryParamMap属性,触发Cannot read properties of undefined (reading 'pipe')错误。

修改方案

需要为mock的ActivatedRoute添加queryParamMap属性,且该属性必须返回Observable类型的值,匹配Angular原生ActivatedRoute的类型定义。

步骤1:导入必要依赖

在测试文件顶部添加以下导入:

import { of } from 'rxjs';
import { ParamMap, convertToParamMap } from '@angular/router';

步骤2:修改ActivatedRoute的mock配置

更新测试模块中ActivatedRoute的provider配置,新增queryParamMap属性:

{
    provide: ActivatedRoute,
    useValue: {
        snapshot: {
            queryParams: {
                type: 'placeholder',
            }
        },
        routeConfig: {
            path: '',
        },
        // 新增queryParamMap的mock
        queryParamMap: of(convertToParamMap({ type: 'placeholder' }))
    }
}

完整修改后的单元测试代码

import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { NgMaterialModule } from 'your-path-to-ng-material-module';
import { Router, ActivatedRoute, ParamMap, convertToParamMap } from '@angular/router';
import { of } from 'rxjs';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { ContainerComponent } from './container.component';

describe('ContainerComponent', () => {
    let component: ContainerComponent;
    let fixture: ComponentFixture<ContainerComponent>;

    beforeEach(waitForAsync(() => {
        TestBed.configureTestingModule({
            imports: [
                TranslateModule.forRoot(),
                NgMaterialModule,
            ],
            providers: [
                {
                    provide: Router,
                    useValue: { navigate: jest.fn() },
                },
                {
                    provide: ActivatedRoute,
                    useValue: {
                        snapshot: {
                            queryParams: {
                                type: 'placeholder',
                            }
                        },
                        routeConfig: {
                            path: '',
                        },
                        queryParamMap: of(convertToParamMap({ type: 'placeholder' }))
                    }
                },
            ],
            declarations: [ContainerComponent],
            schemas: [CUSTOM_ELEMENTS_SCHEMA]
        }).compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(ContainerComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should create', () => {
        expect(component).toBeTruthy();
    });
});

关键说明

  • convertToParamMap:Angular提供的工具函数,将普通JS对象转换为符合ParamMap接口的实例,模拟URL查询参数结构。
  • of(...):RxJS操作符,将静态值转换为Observable,匹配ActivatedRoute.queryParamMap的原生类型(Observable<ParamMap>)。

内容的提问来源于stack exchange,提问作者kiwi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 22:20:30