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

Angular 19+ng-mocks:如何将模拟管道配置为非独立模式?

Angular 19升级与ng-mocks模拟独立管道问题解决方案

问题回顾

Angular 19默认将组件、指令、管道标记为独立模式,在使用ng-mocks模拟@ngx-translate/core的TranslatePipe时,即使设置了ngMocks.config({ defaultStandalone: false }),仍报错模拟管道被标记为独立,无法在NgModule的declarations中声明。

回答问题1:ng-mocks支持全局或按实例覆盖独立标识

ng-mocks完全支持全局或针对单个模拟实例覆盖独立模式标识,但需注意配置时机和正确用法:

  1. 全局配置时机
    确保ngMocks.config在所有测试执行前加载,推荐在项目的test.ts文件中配置,而非单个测试文件内(单个文件需在describe之前执行):

    // test.ts
    import { ngMocks } from 'ng-mocks';
    
    ngMocks.config({
      defaultStandalone: false,
    });
    
  2. 针对单个管道模拟设置
    如果全局配置未生效,可通过MockInstance显式将模拟的TranslatePipe标记为非独立,在单个测试文件的beforeEach或describe前添加:

    import { MockInstance } from 'ng-mocks';
    import { TranslatePipe } from '@ngx-translate/core';
    
    MockInstance(TranslatePipe, () => ({
      standalone: false,
    }), { permanent: true }); // permanent: true 确保所有测试用例生效
    

    或在MockBuilder中直接指定模拟选项:

    import { MockBuilder } from 'ng-mocks';
    import { TranslatePipe } from '@ngx-translate/core';
    import { YourComponent } from './your.component';
    import { YourModule } from './your.module';
    
    describe('YourComponent', () => {
      beforeEach(() => {
        return MockBuilder(YourComponent, YourModule)
          .mock(TranslatePipe, { standalone: false });
      });
    });
    

回答问题2:自定义非独立虚拟管道是可行替代方案

如果上述ng-mocks配置仍无法解决问题,创建显式非独立的自定义模拟管道是可靠的替代方案:

  1. 创建自定义模拟管道

    // mock-translate.pipe.ts
    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
      name: 'translate',
      standalone: false, // 强制标记为非独立
    })
    export class MockTranslatePipe implements PipeTransform {
      transform(value: string, ...args: any[]): string {
        // 根据测试需求实现逻辑,比如直接返回原字符串或固定值
        return value || '';
      }
    }
    
  2. 在测试模块中声明该管道
    在测试配置中,用自定义管道替换ng-mocks的自动模拟:

    import { TestBed } from '@angular/core/testing';
    import { YourComponent } from './your.component';
    import { MockTranslatePipe } from './mock-translate.pipe';
    
    describe('YourComponent', () => {
      beforeEach(async () => {
        await TestBed.configureTestingModule({
          declarations: [YourComponent, MockTranslatePipe], // 声明自定义管道
        }).compileComponents();
      });
    });
    

额外迁移建议

  • 逐步迁移:先将测试中依赖的核心库模拟组件/管道改为非独立,再逐步迁移业务代码至独立模式
  • 检查ng-mocks版本:确保使用最新版ng-mocks,新版本通常会适配Angular 19的独立模式特性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 04:11:09