LoginSignup
4
1

More than 5 years have passed since last update.

Angular コンポーネントのテスト(sample6 / 入出力を伴うコンポーネントのテスト)

Last updated at Posted at 2018-03-24

目次:Angular コンポーネントのテスト


この章では @Input @Output デコレータを利用したコンポーネントのテストについて説明します。

コンポーネントの作成

まずテストを書くためのコンポーネントを作成します。

このコンポーネントは string型の name を受け取ります。
テンプレートにはボタンがひとつあり、クリックすると greet イベントを発生させます。

$ ng generate component sample6
// sample6.component.ts

import {
  Component,
+  EventEmitter,
+  Input,
  OnInit,
+  Output
} from '@angular/core';

@Component({
  selector: 'app-sample6',
  templateUrl: './sample6.component.html',
  styleUrls: ['./sample6.component.css']
})
export class Sample6Component implements OnInit {
+  @Input() name: string;
+  @Output() greet = new EventEmitter<string>();

+  click() {
+    this.greet.emit(`Hello ${this.name}!`);
+  }
  ...
}
// sample6.component.html

- <p>
-   sample6 works!
- </p>

+ <span name="name">{{name}}</span>
+ <button type="button" (click)="click()">greet</button>

@Input の検証

// sample6.component.spec.ts

+ import { By } from '@angular/platform-browser';

+  it('@Input の検証', () => {
+    component.name = 'foo';
+    fixture.detectChanges();
+
+    const element = fixture.debugElement.query(By.css('[name=name]')).nativeElement as HTMLSpanElement;
+    expect(element.textContent).toBe('foo');
+  });

@Output の検証

EventEmitter は emit(イベントの発生)と subscribe(イベントの受け取り)の2つのメソッドを持っています。
subscribe にコールバック関数を渡す事でイベントの発生を検証する事ができます。

Angular v5.2.8 event_emitter.ts
https://github.com/angular/angular/blob/5.2.8/packages/core/src/event_emitter.ts

// sample6.component.spec.ts

+  it('@Output の検証', () => {
+    component.name = 'bar';
+    let message: string;
+
+    component.greet.subscribe(data => message = data);
+
+    const button = fixture.debugElement.query(By.css('button')).nativeElement as HTMLButtonElement;
+    button.click();
+
+    expect(message).toBe('Hello bar!');
+  });

公式ドキュメント Component with inputs and outputs
https://angular.io/guide/testing#component-with-inputs-and-outputs


目次に戻る

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1