1
1

More than 3 years have passed since last update.

Angular Jasmine + Karma でテスト

Last updated at Posted at 2021-03-31

・Jasmine + Karma で単体テスト
Jasmine:テストフレームワーク
Karma:タスクランナーでコードが書き換わるたびに実行

Jasmineでテストコードを書く

テストコードは.spec.tsの名称のファイルに記述する必要がある。
コンポーネント作成する際に対になる形で.spec.tsファイルも自動生成される。

app.componentにtitleを追加。
テストコードでtitleの値が「my-app」であるかテストする。

app.component.ts
export class AppComponent {
  title = 'my-app';
}
app.component.spec.ts
import { TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';

describe('AppComponent', () => {
  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  });

  it('titleは"app"', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;
    expect(app.title).toEqual('my-app');
  });
});

テスト実行

下記コマンドで実行

ng test

成功の場合
5.png
失敗の場合(「my-app」を「app」に変更)
6.png

期待値のチェック

・期待値との完全一致をチェック  toEqual()            
・期待値が含まれるかをチェック  toContains()
・返り値がTrueかどうかをチェック toBeTrusty()
・返り値がundefinedかをチェック expect(a.foo).toBeDefined()
・返り値がundefinedかをチェック expect(a.foo).toBeUndefined()
・返り値がnullかをチェック    expect(a.foo).toBeNull()

1
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
1
1