By 類別選擇器

Angular 的測試模組中,By 類別提供了多種選擇器方法來找到測試中的元素。有以下這些選擇器方法:

By 選擇器方法

  1. By.css(selector: string)

    • 使用 CSS 選擇器查詢元素

    const elements = fixture.debugElement.queryAll(By.css('.some-class'));
  2. By.directive(directive: Type<any>)

    • 查詢特定指令或元件的實例

    const buttons = fixture.debugElement.queryAll(By.directive(MatButton));
  3. By.all()

    • 匹配所有元素

    const allElements = fixture.debugElement.queryAll(By.all());
  4. By.id(id: string)

    • 透過 HTML id 屬性查詢元素

    const element = fixture.debugElement.query(By.id('my-button'));
  5. By.className(className: string)

    • 透過 CSS 類名查詢元素

    const elements = fixture.debugElement.queryAll(By.className('active'));
  6. By.attributeContainingValue(name: string, value: string)

    • 查詢包含特定屬性值的元素

    const elements = fixture.debugElement.queryAll(By.attributeContainingValue('title', 'info'));
  7. By.xpath(path: string)

    • 使用 XPath 表達式查詢元素(不常用)

    const elements = fixture.debugElement.queryAll(By.xpath('//div[@class="container"]/button'));

自定義選擇器

你還可以創建自己的選擇器函數來實現更複雜的查詢邏輯:

// 建立自定義選擇器
const byTextContent = (text: string) => {
  return (debugElement: DebugElement) => {
    const element = debugElement.nativeElement;
    return element.textContent && element.textContent.trim() === text;
  };
};

// 使用自定義選擇器
const element = fixture.debugElement.query(byTextContent('Click me'));

這些選擇器方法能夠幫助你在測試中精確定位到你需要測試的 DOM 元素,從而使測試更加精確和可靠。

Last updated