Angular Academy · 课时

TestBed 与组件夹具

在测试中配置并创建组件

第 1 / 4 课13 个步骤

TestBed 与组件夹具 是 CoddyKit 上的免费 Angular Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Angular Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Angular Academy 课程共包含 4 节课。

为什么需要 TestBed

Angular 组件依赖框架提供的功能:依赖注入、变更检测和模板编译器。要单独测试组件,您需要一个小型的 Angular 环境。TestBed 是 Angular 的主要测试工具,会为每个测试构建这个环境。

它会配置一个临时 NgModule,编译您的组件,并提供一个用于与组件交互的句柄。

configureTestingModule

TestBed.configureTestingModule() 声明测试所需的内容:待测试组件、其提供程序以及所有导入项。对于独立组件,请将组件本身放入 imports 中。

import { TestBed } from '@angular/core/testing';
import { CounterComponent } from './counter.component';

beforeEach(() => {
  TestBed.configureTestingModule({
    imports: [CounterComponent],
  });
});

创建组件测试夹具

TestBed.createComponent(CounterComponent) 返回一个 ComponentFixture。测试夹具就像您的遥控器:它封装了组件实例、组件的原生 DOM 元素以及变更检测机制。

import { ComponentFixture, TestBed } from '@angular/core/testing';

let fixture: ComponentFixture<CounterComponent>;

beforeEach(() => {
  fixture = TestBed.createComponent(CounterComponent);
});

访问组件实例

fixture.componentInstance 是实际的类实例。您可以直接调用它的方法并读取它的属性,就像使用普通 TypeScript 一样。

it('creates the component', () => {
  const fixture = TestBed.createComponent(CounterComponent);
  const component = fixture.componentInstance;
  expect(component).toBeTruthy();
  expect(component.count).toBe(0);
});

detectChanges 触发渲染

新创建的测试夹具尚未完成渲染。调用 fixture.detectChanges() 来运行变更检测和组件的 ngOnInit,将绑定数据写入 DOM。

it('renders initial value', () => {
  const fixture = TestBed.createComponent(CounterComponent);
  fixture.detectChanges(); // now bindings are applied
  const el = fixture.nativeElement as HTMLElement;
  expect(el.textContent).toContain('0');
});

nativeElement 与 debugElement

fixture.nativeElement 是原始 DOM 节点(一个 HTMLElement)。fixture.debugElement 是 Angular 提供的功能更丰富的包装器,您可以使用它按指令查询、读取注入的服务并检查绑定。

const native = fixture.nativeElement;       // HTMLElement
const debug = fixture.debugElement;         // DebugElement
console.log(debug.componentInstance === fixture.componentInstance); // true

测试模块中的提供程序

如果组件注入了服务,请通过 providers 提供这些服务。您可以使用真实服务或测试替身。这里我们在一个简单示例中提供真实服务。

TestBed.configureTestingModule({
  imports: [CounterComponent],
  providers: [
    { provide: LoggerService, useValue: { log: () => {} } },
  ],
});

用于外部模板的 compileComponents

使用非内联的 templateUrl/styleUrls,且未使用 Angular CLI 测试设置时,必须异步编译模板。请调用 await TestBed.compileComponents()。使用 CLI 时,通常会自动完成这一步。

beforeEach(async () => {
  await TestBed.configureTestingModule({
    imports: [ProfileComponent],
  }).compileComponents();
});

一个完整的最小测试

把这些步骤组合起来就是:配置、创建、检测、断言。这几乎是每个 Angular 组件测试的标准结构。

describe('CounterComponent', () => {
  let fixture: ComponentFixture<CounterComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({ imports: [CounterComponent] });
    fixture = TestBed.createComponent(CounterComponent);
    fixture.detectChanges();
  });

  it('starts at zero', () => {
    expect(fixture.componentInstance.count).toBe(0);
  });
});

使用 TestBed.inject 获取服务

要获取已配置的提供程序,请使用 TestBed.inject(Token)。这是已弃用的 TestBed.get() 的现代替代方案。

const logger = TestBed.inject(LoggerService);
expect(logger).toBeDefined();

在测试之间重置

TestBed 会在每个测试前自动重置其模块,因此提供程序和组件状态不会泄漏。这就是为什么您应在 beforeEach 中进行配置,而不是在全局范围内只配置一次。

快速检查

测试在 createComponent 之后立即发生什么。

回顾

您学习了测试的核心:TestBed.configureTestingModule() 构建环境,createComponent() 返回 ComponentFixture,而 detectChanges() 负责渲染。使用 componentInstance 访问类,使用 nativeElement/debugElement 访问 DOM,使用 TestBed.inject() 获取服务。

免费开始

用 AI 导师学习 HTML — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
38
课程
144

常见问题解答

「TestBed 与组件夹具」课时是免费的吗?

是的 — 「TestBed 与组件夹具」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Angular Academy 课程的其余内容,请升级到 CoddyKit PRO。 Angular Academy 课程共包含 4 节课。

「TestBed 与组件夹具」这节课中我会学到什么?

在测试中配置并创建组件 你通过在浏览器中直接运行的动手代码来练习 Angular Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Angular Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Angular Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「TestBed 与组件夹具」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Angular Academy 课中编写并运行代码吗?

能。每节 Angular Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. TestBed 与组件夹具
  2. 测试输入、输出和 DOM
  3. 模拟服务与依赖项
  4. 测试信号与异步代码
← 返回 Angular Academy