Angular 測(cè)試管道

2022-07-08 09:21 更新

測(cè)試管道

你可以在沒有 Angular 測(cè)試工具的情況下測(cè)試管道。

如果你要試驗(yàn)本指南中所講的應(yīng)用,請(qǐng)在瀏覽器中運(yùn)行它下載并在本地運(yùn)行它。

測(cè)試 TitleCasePipe

這個(gè)管道類有一個(gè)方法 ?transform?,它把輸入值變成一個(gè)轉(zhuǎn)換后的輸出值。?transform ?的實(shí)現(xiàn)很少會(huì)與 DOM 交互。除了 ?@Pipe? 元數(shù)據(jù)和一個(gè)接口之外,大多數(shù)管道都不依賴于 Angular。

考慮一個(gè) ?TitleCasePipe?,它會(huì)把每個(gè)單詞的第一個(gè)字母大寫。這里是通過正則表達(dá)式實(shí)現(xiàn)的。

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(/\w\S*/g, (txt => txt[0].toUpperCase() + txt.slice(1).toLowerCase() ));
  }
}

任何使用正則表達(dá)式的東西都值得徹底測(cè)試。使用簡(jiǎn)單的 Jasmine 來探索預(yù)期的案例和邊緣情況。

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 測(cè)試來支持管道測(cè)試

這些都是對(duì)管道進(jìn)行隔離測(cè)試的。他們無法判斷當(dāng) ?TitleCasePipe ?應(yīng)用于組件中時(shí)是否能正常運(yùn)行。

考慮添加這樣的組件測(cè)試:

it('should convert hero name to Title Case', () => {
  // get the name's 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');
});


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)