在前面幾天,我們建立了一個簡單的 Todo API,並且加入了路由、CRUD、資料庫、驗證與 Middleware。不過,隨著功能越來越多,光靠「手動測試」API(用 Postman 或 curl)已經不太夠用了。
這時候,就需要 自動化測試 來幫助我們:
今天,我們會用 Jest + Supertest 來完成 Todo API 的自動化測試。
安裝方式:
npm install --save-dev jest supertest
在 package.json 中加上測試指令:
"scripts": {
"test": "jest"
}
建立一個 tests/todo.test.js 檔案,內容如下:
const request = require('supertest');
const app = require('../app'); // 引入 Express app
describe('Todo API', () => {
it('應該回傳所有 Todos', async () => {
const res = await request(app).get('/api/todos');
expect(res.statusCode).toEqual(200);
expect(Array.isArray(res.body)).toBe(true);
});
});
說明:
it('應該建立一個新的 Todo', async () => {
const res = await request(app)
.post('/api/todos')
.send({ title: 'Test Todo' });
expect(res.statusCode).toEqual(201);
expect(res.body).toHaveProperty('_id');
expect(res.body.title).toBe('Test Todo');
});
it('應該取得特定 Todo', async () => {
const newTodo = await request(app)
.post('/api/todos')
.send({ title: 'Fetch Me' });
const res = await request(app).get(`/api/todos/${newTodo.body._id}`);
expect(res.statusCode).toEqual(200);
expect(res.body.title).toBe('Fetch Me');
});
it('應該更新 Todo', async () => {
const newTodo = await request(app)
.post('/api/todos')
.send({ title: 'Update Me' });
const res = await request(app)
.put(`/api/todos/${newTodo.body._id}`)
.send({ title: 'Updated Todo' });
expect(res.statusCode).toEqual(200);
expect(res.body.title).toBe('Updated Todo');
});
it('應該刪除 Todo', async () => {
const newTodo = await request(app)
.post('/api/todos')
.send({ title: 'Delete Me' });
const res = await request(app).delete(`/api/todos/${newTodo.body._id}`);
expect(res.statusCode).toEqual(200);
expect(res.body).toHaveProperty('message', 'Todo deleted');
});
在終端機執行:
npm test
如果一切正常,會看到類似輸出:
PASS tests/todo.test.js
Todo API
應該回傳所有 Todos (50 ms)
應該建立一個新的 Todo (30 ms)
應該取得特定 Todo (25 ms)
應該更新 Todo (28 ms)
應該刪除 Todo (26 ms)
今天我們學會了:
到這裡,我們的 Todo API 已經不只是能跑,還能確保「每次修改都不會出錯」!