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

如何使用Spectator测试Angular 14独立组件?

使用Spectator测试Angular独立组件(Jest环境)

错误原因

你遇到的报错是因为独立组件(standalone: true)不能被添加到declarations数组,Angular要求独立组件必须通过imports引入,而旧的Spectator配置习惯把组件放在declarations里,这就触发了Angular的校验错误。

正确配置方式

使用Spectator测试独立组件时,只需调整createComponentFactory的配置,移除冗余的declarations,直接指定组件并按需配置imports即可:

import { createComponentFactory, Spectator } from '@ngneat/spectator/jest';
import { OurComponent } from './our.component';

describe('OurComponent', () => {
  let spectator: Spectator<OurComponent>;
  const createComponent = createComponentFactory({
    // 直接指定要测试的独立组件
    component: OurComponent,
    // 组件依赖的其他独立组件、指令、管道或NgModule,都放在这里
    imports: [/* 比如:OtherStandaloneComponent, CommonModule */],
    // 可选:控制是否自动触发变更检测,默认true
    detectChanges: false,
    // 可选:提供mock服务或依赖
    providers: [/* Mock providers */]
  });

  beforeEach(() => {
    spectator = createComponent();
  });

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

  it('should render input value', () => {
    // 传递输入属性
    spectator.setInput('title', 'Hello Spectator');
    spectator.detectChanges();
    
    expect(spectator.query('h1')).toHaveText('Hello Spectator');
  });
});

核心注意事项

  • 完全移除declarations数组:独立组件不允许被声明在任何模块中,Spectator会自动处理组件的导入逻辑
  • 依赖管理:如果组件用到了其他独立组件、第三方模块(比如CommonModule),必须添加到imports数组
  • 输入输出处理:可以通过createComponent({ props: {...} })初始化时传递输入,或用spectator.setInput()动态修改
  • DOM操作:Spectator提供了spectator.query()、spectator.queryAll()等快捷方法,替代fixture.debugElement.query()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 10:45:35