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

如何用ng-mocks渲染未被指令或组件包裹的独立模板?

解决Angular独立ng-template的ng-mocks测试问题

要测试组件内未被指令/组件包裹的独立<ng-template>,可以通过以下原生Angular测试结合ng-mocks的方式实现:

步骤1:在被测组件中声明模板引用

首先确保组件通过@ViewChild获取目标模板的引用:

import { Component, TemplateRef, ViewChild } from '@angular/core';

@Component({
  selector: 'my-component',
  template: `<ng-template #tpl>{{ whatever }}</ng-template>`,
})
export class MyComponent {
  @ViewChild('tpl') tpl: TemplateRef<any>;
}

步骤2:在测试中手动创建嵌入式视图

不需要依赖ng-mocks的render函数,直接通过MockRender渲染组件后,获取模板引用并手动创建视图:

import { TestBed } from '@angular/core/testing';
import { MyComponent } from './my.component';
import { MockBuilder, MockRender } from 'ng-mocks';

describe('MyComponent', () => {
  beforeEach(() => MockBuilder(MyComponent));

  it('should render correct template content', () => {
    // 渲染组件实例
    const fixture = MockRender(MyComponent);
    const component = fixture.componentInstance;
    
    // 获取组件内的模板引用
    const templateRef = component.tpl;
    // 创建嵌入式视图并传入上下文数据
    const viewRef = fixture.nativeElement.createEmbeddedView(templateRef, { whatever: '预期测试文本' });
    
    // 触发变更检测更新视图
    fixture.detectChanges();
    
    // 验证模板渲染内容
    expect(viewRef.rootNodes[0].textContent.trim()).toBe('预期测试文本');
  });
});

关键说明

  • MockRender负责完成组件的实例化和依赖注入,之后可以像常规Angular测试一样操作组件实例和模板引用。
  • 手动创建EmbeddedView是Angular原生的测试手段,无需额外依赖ng-mocks的特殊API,就能直接验证独立模板的渲染逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 22:04:50