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

组件单元测试报错:Cannot read properties of undefined (reading 'reposition')

解决MatSelect单元测试中'reposition'未定义的报错

问题情况

对组件进行单元测试时持续报错:
Cannot read properties of undefined (reading 'reposition') at MatSelect.eval [as _scrollStrategyFactory]
已在spec文件的imports中导入MatSelectModule和MatOptionModule,但仍触发[object ErrorEvent]错误

解决方案

  • 本质原因是MatSelect依赖Angular CDK的Overlay模块提供滚动策略,单元测试环境里没正确配置这些依赖,下面是几种可行的解决方法:

方法一:导入OverlayModule并提供模拟的滚动策略配置

在测试文件的TestBed配置里,添加OverlayModule到导入列表,同时提供ScrollStrategyOptions的模拟实现:

import { OverlayModule, ScrollStrategyOptions } from '@angular/cdk/overlay';

TestBed.configureTestingModule({
  imports: [
    MatSelectModule,
    MatOptionModule,
    OverlayModule
  ],
  providers: [
    {
      provide: ScrollStrategyOptions,
      useValue: {
        reposition: () => jasmine.createSpyObj('ScrollStrategy', ['attach', 'detach'])
      }
    }
  ]
});

方法二:补全依赖模块

如果组件用到了动画,还需要导入BrowserAnimationsModule,确保所有相关依赖都被包含:

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { OverlayModule } from '@angular/cdk/overlay';

TestBed.configureTestingModule({
  imports: [
    MatSelectModule,
    MatOptionModule,
    OverlayModule,
    BrowserAnimationsModule
  ]
});

方法三:手动Mock滚动策略工厂函数

在测试初始化环节,直接获取MatSelect实例并mock掉报错的方法:

import { By } from '@angular/platform-browser';
import { MatSelect } from '@angular/material/select';

beforeEach(() => {
  fixture = TestBed.createComponent(YourComponent);
  component = fixture.componentInstance;
  // 获取页面中的MatSelect实例
  const matSelect = fixture.debugElement.query(By.directive(MatSelect)).componentInstance;
  // Mock滚动策略工厂,返回包含reposition方法的对象
  matSelect._scrollStrategyFactory = () => ({
    reposition: () => {}
  });
  fixture.detectChanges();
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 19:54:39