Express.js アプリのテスト
express-generator で作成された標準的な Express アプリ用の「 テストファイル 」の作成・実行をしてみます。
まず、テスト関連パッケージをインストールするために以下のコマンドを実行します。
npm install --save-dev jest supertest
package.json にスクリプト追加します。
package.json
{
"name": "test",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www",
"test": "jest"
},
"dependencies": {
"cookie-parser": "~1.4.4",
"debug": "~2.6.9",
"ejs": "^3.1.10",
"express": "^5.0.1",
"http-errors": "~1.6.3",
"morgan": "~1.9.1"
},
"devDependencies": {
"jest": "^30.0.4",
"supertest": "^7.1.3"
}
}
Express.js のアプリに「 test 」ディレクトリを作成します。
- your-app
- app.js
- routes
- index.js
- users.js
- test
- app.test.js
- ...
test/app.test.jsを以下のように編集します。
test/app.test.js
const request = require('supertest');
const app = require('../app');
describe('GET /', () => {
it('should respond with 200 OK and contain HTML', async () => {
const res = await request(app).get('/');
expect(res.statusCode).toBe(200);
expect(res.headers['content-type']).toMatch(/html/);
expect(res.text).toMatch(/Welcome|Express/i); // テンプレートに合わせて調整
});
});
describe('GET /users', () => {
it('should respond with 200 OK (or 404 if route not implemented)', async () => {
const res = await request(app).get('/users');
expect([200, 404]).toContain(res.statusCode); // 初期状態では 404 の可能性もあり
});
});
以下のコマンドを実行するとテストが実行されます。
npm test
以下は実行結果のサンプルです。
npm test
> test@0.0.0 test
> jest
GET / 200 8.197 ms - 207
GET /users 200 1.013 ms - 23
PASS test/app.test.js
GET /
√ should respond with 200 OK and contain HTML (37 ms)
GET /users
√ should respond with 200 OK (or 404 if route not implemented) (6 ms)
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 3.86 s
Ran all test suites.
テストコードの解説
describe('GET /', () => {
it('should respond with 200 OK and contain HTML', async () => {
const res = await request(app).get('/');
expect(res.statusCode).toBe(200);
expect(res.headers['content-type']).toMatch(/html/);
expect(res.text).toMatch(/Welcome|Express/i); // テンプレートに合わせて調整
});
});
describe('GET /', () => { ... });
テストのグループを定義します。'GET /' は、テストの対象が「トップページ(/)」であることを意味します。
このブロック内に複数のテスト(it(...))を書くことができます。
it('should respond with 200 OK and contain HTML', async () => { ... });
個々のテストケース(仕様)を定義します。
'should respond with 200 OK and contain HTML' はこのテストの目的です。
const res = await request(app).get('/');
Supertest を使って、アプリ(app)に対して HTTP GET リクエストを / に送っています。
expect(res.statusCode).toBe(200);
ステータスコードが 200 OK であることを確認しています。
expect(res.headers['content-type']).toMatch(/html/);
レスポンスの Content-Type ヘッダーが HTML(例:text/html; charset=utf-8)であることを確認します。
/html/ は正規表現で、content-type の文字列に "html" が含まれているかをチェックします。
expect(res.text).toMatch(/Welcome|Express/i);
レスポンス本文(HTMLの中身)に Welcome または Express という文字列が含まれているかをチェックします。
ファイルごとのテスト実行方法(Jest)
ファイルごとにテストを実行するには以下のようにします。
npx jest test/math.test.js
package.json に "test": "jest" としてある場合、以下の方法でも実行できます。
npm test -- test/math.test.js
describe や it 単位で実行したい場合は、以下のようにします。
npx jest -t "should return 200"