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

Angular Safe Pipe单元测试报错:bypassSecurityTrustResourceUrl不是函数

解决SafeUrlPipe单元测试报错:this.sanitizer.bypassSecurityTrustResourceUrl is not a function

问题根源

你在实例化SafeUrlPipe时传入的是空对象(<DomSanitizer>{}),这个模拟的DomSanitizer没有实现bypassSecurityTrustResourceUrl方法,导致调用transform时触发方法不存在的错误。

解决方案

需要创建一个带有模拟方法的DomSanitizer对象,确保bypassSecurityTrustResourceUrl方法存在,同时还能验证方法的调用逻辑。

基于Jasmine的测试代码

it('should return safe url', () => {
  // 创建带有mock方法的DomSanitizer模拟对象
  const mockSanitizer = jasmine.createSpyObj('DomSanitizer', ['bypassSecurityTrustResourceUrl']);
  // 指定mock方法的返回值
  const mockSafeUrl = 'safe-val' as SafeResourceUrl;
  mockSanitizer.bypassSecurityTrustResourceUrl.and.returnValue(mockSafeUrl);

  const pipe = new SafeUrlPipe(mockSanitizer);
  const result = pipe.transform('val');

  // 验证sanitizer方法是否被正确调用
  expect(mockSanitizer.bypassSecurityTrustResourceUrl).toHaveBeenCalledWith('val');
  // 验证返回值符合预期
  expect(result).toBe(mockSafeUrl);
  expect(pipe).toBeTruthy();
});

基于Jest的测试代码

it('should return safe url', () => {
  // 模拟DomSanitizer对象及方法
  const mockSanitizer = {
    bypassSecurityTrustResourceUrl: jest.fn().mockReturnValue('safe-val' as SafeResourceUrl)
  } as unknown as DomSanitizer;

  const pipe = new SafeUrlPipe(mockSanitizer);
  const result = pipe.transform('val');

  expect(mockSanitizer.bypassSecurityTrustResourceUrl).toHaveBeenCalledWith('val');
  expect(result).toBe('safe-val');
  expect(pipe).toBeTruthy();
});

补充说明

之前的测试仅验证pipe实例存在,没有覆盖transform的核心逻辑。通过模拟DomSanitizer的方法,不仅能解决报错问题,还能验证:

  • bypassSecurityTrustResourceUrl是否被传入正确的参数调用
  • transform是否正确返回了sanitizer处理后的结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 20:10:27