Categories: Angular13 教程

Angular 测试管道

测试管道

你可以在没有 Angular 测试工具的情况下测试管道。

如果你要试验本指南中所讲的应用,请在浏览器中运行它下载并在本地运行它

测试 TitleCasePipe

这个管道类有一个方法 ​transform​,它把输入值变成一个转换后的输出值。​transform ​的实现很少会与 DOM 交互。除了 ​@Pipe​ 元数据和一个接口之外,大多数管道都不依赖于 Angular。

考虑一个 ​TitleCasePipe​,它会把每个单词的第一个字母大写。这里是通过正则表达式实现的。

import { Pipe, PipeTransform } from @angular/core;

@Pipe({name: titlecase, pure: true})
/** Transform to Title Case: uppercase the first letter of the words in a string. */export class TitleCasePipe implements PipeTransform {
  transform(input: string): string {
    return input.length === 0 ?  :
      input.replace(/wS*/g, (txt => txt[0].toUpperCase() + txt.slice(1).toLowerCase() ));
  }
}

任何使用正则表达式的东西都值得彻底测试。使用简单的 Jasmine 来探索预期的案例和边缘情况。

describe(TitleCasePipe, () => {
  // This pipe is a pure, stateless function so no need for BeforeEach
  const pipe = new TitleCasePipe();

  it(transforms "abc" to "Abc", () => {
    expect(pipe.transform(abc)).toBe(Abc);
  });

  it(transforms "abc def" to "Abc Def", () => {
    expect(pipe.transform(abc def)).toBe(Abc Def);
  });

  // ... more tests ...
});

编写 DOM 测试来支持管道测试

这些都是对管道进行隔离测试的。他们无法判断当 ​TitleCasePipe ​应用于组件中时是否能正常运行。

考虑添加这样的组件测试:

it(should convert hero name to Title Case, () => {
  // get the names input and display elements from the DOM
  const hostElement: HTMLElement = fixture.nativeElement;
  const nameInput: HTMLInputElement = hostElement.querySelector(input)!;
  const nameDisplay: HTMLElement = hostElement.querySelector(span)!;

  // simulate user entering a new name into the input box
  nameInput.value = quick BROWN  fOx;

  // Dispatch a DOM event so that Angular learns of input value change.
  nameInput.dispatchEvent(new Event(input));

  // Tell Angular to update the display binding through the title pipe
  fixture.detectChanges();

  expect(nameDisplay.textContent).toBe(Quick Brown  Fox);
});

andy

前端小白,在Web176教程网这个平台跟大家一起学习,加油!

Share
Published by
andy

Recent Posts

聊聊vue3中的defineProps

在Vue 3中,defineP…

1 周 ago

在 Chrome 中删除、允许和管理 Cookie

您可以选择删除现有 Cooki…

2 周 ago

自定义指令:聊聊vue中的自定义指令应用法则

今天我们来聊聊vue中的自定义…

3 周 ago

聊聊Vue中@click.stop和@click.prevent

一起来学下聊聊Vue中@cli…

4 周 ago

Nginx 基本操作:启动、停止、重启命令。

我们来学习Nginx基础操作:…

1 月 ago

Vue3:手动清理keep-alive组件缓存的方法

Vue3中手动清理keep-a…

1 月 ago