第08章 運用・テスト
NestJS はテスト容易性・運用性を重視して設計されています。 ここでは以下の機能を扱います:
- テスト(ユニットテスト / E2E テスト)
- 設定管理(ConfigModule)
- キャッシュ(Redis 等)
- ロギング
8.1 テスト
NestJS は Jest を標準テストランナーとしてサポート。
ユニットテスト例
import { Test, TestingModule } from '@nestjs/testing';
import { AppService } from './app.service';
describe('AppService', () => {
let service: AppService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [AppService],
}).compile();
service = module.get<AppService>(AppService);
});
it('should return "Hello World!"', () => {
expect(service.getHello()).toBe('Hello World!');
});
});
E2E テスト例
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { AppModule } from './../src/app.module';
describe('AppController (e2e)', () => {
let app: INestApplication;
beforeAll(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
it('/ (GET)', () => {
return request(app.getHttpServer())
.get('/')
.expect(200)
.expect('Hello World!');
});
});
➡️ npm run test:e2e で実行可能。
8.2 設定管理(ConfigModule)
アプリの環境変数や設定を集中管理できる。
インストール
npm install --save @nestjs/config
設定ファイル
.env
DB_HOST=localhost
DB_PORT=3306