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

如何在Angular测试中提供HostAttributeToken?

在Angular Jasmine/Karma测试中提供HostAttributeToken的解决方案

问题背景

我最近在Angular中发现了HostAttributeToken,它可以用于为组件提供静态属性。以下是正常运行的组件代码:

import { Component, HostAttributeToken, inject } from '@angular/core';

@Component({
  selector: 'demo-component',
  template: `<div [class]="styleClass">Hello world</div>`,
})
export class DemoComponent {
  styleClass = inject(new HostAttributeToken('style-class'));
}

组件的使用方式:

<demo-component style-class="bla" />

我现在的问题是:如何在Jasmine/Karma测试中提供这个HostAttributeToken?我希望将该属性设置为必填(HostAttributeToken本身也支持可选标记)。如果有宿主组件的话实现起来很简单,但如何通过TestBed API实现相同效果?

当前未提供HostAttributeToken的测试代码运行时会报错:

Error: NG0201: No provider for HostAttributeToken style-class found.

基础测试代码如下:

import { TestBed } from '@angular/core/testing';
import { DemoComponent } from './demo.component';

describe('DemoComponent', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [DemoComponent],
    }).compileComponents();
  });

  it('should create', () => {
    const fixture = TestBed.createComponent(DemoComponent);
    expect(fixture.componentInstance).toBeTruthy();
  });
});

解决方案

方法一:直接在TestBed中提供HostAttributeToken依赖

HostAttributeToken本质是Angular的DI注入令牌,你可以直接在configureTestingModule的providers数组中配置它的提供者,指定对应的值:

修改后的测试代码如下:

import { TestBed } from '@angular/core/testing';
import { DemoComponent } from './demo.component';
import { HostAttributeToken } from '@angular/core';

describe('DemoComponent', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [DemoComponent],
      providers: [
        // 提供HostAttributeToken的实例,指定测试用的值
        {
          provide: new HostAttributeToken('style-class'),
          useValue: 'test-style-class'
        }
      ]
    }).compileComponents();
  });

  it('should create', () => {
    const fixture = TestBed.createComponent(DemoComponent);
    expect(fixture.componentInstance).toBeTruthy();
    // 额外验证注入的值是否符合预期
    expect(fixture.componentInstance.styleClass).toBe('test-style-class');
  });
});

方法二:测试必填属性的异常场景

如果你想验证未提供该属性时组件会抛出错误(即必填逻辑),可以编写专门的测试用例:

it('should throw error when style-class attribute is not provided', () => {
  // 重置TestBed配置,不提供HostAttributeToken
  TestBed.configureTestingModule({
    imports: [DemoComponent]
  });

  // 验证创建组件时会抛出对应的NG0201错误
  expect(() => TestBed.createComponent(DemoComponent)).toThrowError(/NG0201/);
});

原理说明

HostAttributeToken的工作机制依赖Angular的依赖注入系统,当组件通过inject获取该令牌时,Angular会从DI容器中查找对应的提供者。在测试环境中,TestBed就是我们的DI容器,所以直接在providers中配置令牌和对应的值,就能让组件正常获取到所需的属性值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 19:37:15