LoginSignup
7
9

More than 5 years have passed since last update.

Angular jasmine 使い方メモ

Last updated at Posted at 2017-11-14

はじめに

Angularでユニットテストを作成したときに使用したjasmineの使い方をメモしていきます。

alertが表示されることをテスト

beforeEach(() => {

  // アラートの監視
  spyOn(window, 'alert');
});

it('〇〇な場合、対応するアラートを表示するべきである', () => {

    // テストを実行
    component.testSample();

    // テスト結果検証
    expect(window.alert).toHaveBeenCalledWith('エラー');
});

it('〇〇な場合、アラートを表示するべきでない', () => {

    // テストを実行
    component.testSample();

    // テスト結果検証
    expect(window.alert).not.toHaveBeenCalled();
});

protected privateな関数が呼び出されているかをテスト

let component: CsvJsonParseDemoComponent;
let fixture: ComponentFixture<xxxComponent>;

beforeEach(() => {
    fixture = TestBed.createComponent(xxxComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
});
describe('xxxComponent', () => {
   describe('testSample1', () => {
      it('testSample1を実行した場合、testSample2関数を呼ぶべきである', () => {
          // testSample2を監視
          spyOn((component as any), 'testSample2');
          // テストを実行
          component.testSample1();
        // テスト結果検証
        expect((component as any).testSample2).toHaveBeenCalled();
    });
   }
}

固定の戻り値を返却

spyOn((component as any), 'testSample1').and.returnValue('引数');

// 非同期の場合
spyOn((component as any), 'testSample1').and.returnValue(Promise.resolve('引数'));

戻り値がObservableで、delayを使用している関数のテスト

// 例として作成した関数
getContentsAsObservable(): Observable<any> {
   // 1秒後にhogeした内容を返す
   return Observable.of(~~ hoge ~~).delay(1000);
}
import { fakeAsync, tick, discardPeriodicTasks } from '@angular/core/testing';

it(`テストしてみよう`, fakeAsync(() => {
  component.getContentsAsObservable()
   .subscribe((result) => {
     expect(result).toEqual('~~ hoge ~~');
  });
  tick(1001);
 discardPeriodicTasks();
}

discardPeriodicTasks()を呼ぶことでfakeAsync 中で残っている不要なタスクを終了します。
呼ばないと以下のエラーが出るので注意。

Error: 4 periodic timer(s) still in the queue.

[Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest']エラーが発生したときの対処法

以下のコマンドで実際のエラーを吐かせる。

$ ng test -sm=false
7
9
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
7
9