Angular CLIで生成されるspec.tsファイルの役割
Angular CLIで生成されるspec.tsファイル
spec.tsファイルとは
spec.tsファイルは、単体テスト用のファイルです。単体テストとは、個々のコンポーネントやサービスなど、アプリケーションの小さな部分を独立してテストする方法です。
spec.tsファイルには、以下の内容が含まれます。
- テスト対象のコンポーネントやサービスをimportする記述
- テストケースを記述する
describe
とit
ブロック - テストコード
- コードの品質を向上させる
- バグを早期に発見する
- コードの変更に伴う影響を検証する
spec.tsファイルは、Jasmineというテストフレームワークを使用して記述します。Jasmineの詳細については、Jasmine公式ドキュメント: URL Jasmineを参照してください。
import { Component, OnInit } from '@angular/core';
import { By } from '@angular/platform-browser';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor() {}
ngOnInit() {}
}
describe('AppComponent', () => {
beforeEach(() => {
// テスト対象のコンポーネントを生成
const fixture = TestBed.createComponent(AppComponent);
// コンポーネントのインスタンスを取得
const component = fixture.componentInstance;
});
it('should create the app', () => {
// テストコード
expect(component).toBeTruthy();
});
});
この例では、AppComponent
というコンポーネントに対する単体テストが記述されています。
spec.tsファイルは、Angularアプリケーション開発において重要な役割を果たします。単体テストを記述することで、コードの品質を向上させ、バグを早期に発見することができます。
- Angular公式ドキュメント - Testing: URL Angular Testing
- Jasmine公式ドキュメント: URL Jasmine
// app.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'Angular App';
constructor() {}
ngOnInit() {}
}
// app.component.spec.ts
import { Component, OnInit } from '@angular/core';
import { By } from '@angular/platform-browser';
import { TestBed } from '@angular/core/testing';
describe('AppComponent', () => {
beforeEach(() => {
// テスト対象のコンポーネントを生成
const fixture = TestBed.createComponent(AppComponent);
// コンポーネントのインスタンスを取得
const component = fixture.componentInstance;
});
it('should create the app', () => {
// テストコード
expect(component).toBeTruthy();
});
it('should have the correct title', () => {
// テストコード
const fixture = TestBed.createComponent(AppComponent);
const element = fixture.nativeElement;
const h1 = element.querySelector('h1');
expect(h1.textContent).toBe('Angular App');
});
});
it('should create the app', () => {
は、AppComponent
が正しく作成されることをテストします。
テストコードは、expect
関数を使用して、テスト対象のコードの動作を検証します。
- テストコードは、できるだけ詳細に記述する必要があります。
- テストコードは、定期的に実行して、コードの品質を維持する必要があります。
spec.tsファイルの生成方法
Angular CLIコマンドを使用する
ng generate component
コマンドを実行すると、コンポーネントの雛形が生成されます。その中には、spec.ts
ファイルも含まれています。
ng generate component my-component
手動で作成する
spec.tsファイルを手動で作成することもできます。ファイル名は、テスト対象のコンポーネント名と同じ名前にして、spec.ts
という拡張子を付けます。
例えば、MyComponent
というコンポーネントに対するspec.tsファイル名は、my-component.spec.ts
になります。
src/app
ディレクトリ- コンポーネントのディレクトリ
- テスト対象のコンポーネント名と同じ名前にする
spec.ts
という拡張子を付ける
上記の方法を参考に、spec.tsファイルを生成して、単体テストを記述してみましょう。
angular typescript