การทดสอบการเชื่อมต่อปลายทาง API
สร้างการทดสอบการเชื่อมต่อเพื่อตรวจสอบการทำงานร่วมกันระหว่างองค์ประกอบต่าง ๆ และรับรองการทำงานของ API
การทดสอบการเชื่อมต่อปลายทาง API เป็นบทเรียน Node.js Backend Development Bootcamp ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Node.js Backend Development Bootcamp และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Node.js Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
What is Integration Testing?
Welcome! In this lesson, we'll dive into integration testing for Node.js API endpoints. Unlike unit tests (which test small, isolated pieces of code), integration tests verify that different parts of your application work together as expected.
For APIs, this means ensuring your endpoints correctly handle requests, interact with databases or other services, and return the right responses.
Why Test API Endpoints?
Your API is the main way external clients interact with your backend. Robust integration tests ensure:
- Endpoints respond with correct HTTP status codes.
- Data sent to the API is processed and stored properly.
- The API returns expected data formats (e.g., JSON).
- Different components (like routing, middleware, database) integrate seamlessly.
This helps catch bugs early that unit tests might miss.
Essential Testing Tools
To test our Node.js API endpoints, we'll use a couple of key tools:
- Jest: Our test runner and assertion library (introduced in Lesson 1).
- Supertest: A library designed to test HTTP servers. It makes it easy to send requests and assert responses.
- Express: Our web framework, for building the API itself.
Setting Up Supertest
First, let's install the necessary packages. We'll need express for our sample API, and jest and supertest for testing.
Run this command in your project terminal:
npm install --save-dev express jest supertestOur Simple Express App
Let's create a basic Express application that we can test. We'll define a few simple routes.
Notice we export the app instance, which Supertest will use to make requests directly, without needing to start a live server on a port.
const express = require('express');
const app = express();
// Middleware to parse JSON request bodies
app.use(express.json());
// A simple GET route
app.get('/', (req, res) => {
res.send('Hello from Express!');
});
// A GET route that returns JSON
app.get('/data', (req, res) => {
res.json({ message: 'API data', version: 1.0 });
});
// A POST route that echoes the request body
app.post('/echo', (req, res) => {
res.json(req.body);
});
// Export the app for testing purposes
module.exports = app;
// Start the server only if not in a test environment
if (process.env.NODE_ENV !== 'test') {
const port = 3000;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
}Testing a GET Endpoint
Now, let's write our first integration test. We'll use supertest to make a GET request to our root / endpoint and assert its response.
Create a file like app.test.js and add the following:
const request = require('supertest');
const app = require('./app'); // Import our Express app
describe('GET /', () => {
it('should return "Hello from Express!"', async () => {
const res = await request(app).get('/');
expect(res.statusCode).toEqual(200);
expect(res.text).toEqual('Hello from Express!');
});
});Asserting JSON Responses
APIs often return JSON data. Supertest makes it easy to access the parsed JSON body of a response using res.body.
Let's test our /data endpoint to ensure it returns the correct JSON object:
const request = require('supertest');
const app = require('./app');
describe('GET /data', () => {
it('should return JSON with message and version', async () => {
const res = await request(app).get('/data');
expect(res.statusCode).toEqual(200);
expect(res.type).toEqual('application/json');
expect(res.body).toEqual({ message: 'API data', version: 1.0 });
expect(res.body.message).toBe('API data');
});
});Testing POST Requests
Testing POST requests is similar, but we'll use .post() and often .send() to attach a request body.
Our /echo endpoint simply returns whatever JSON it receives. Let's test that functionality:
const request = require('supertest');
const app = require('./app');
describe('POST /echo', () => {
it('should echo the sent JSON data', async () => {
const testData = { name: 'Coddy', score: 95 };
const res = await request(app)
.post('/echo')
.send(testData);
expect(res.statusCode).toEqual(200);
expect(res.type).toEqual('application/json');
expect(res.body).toEqual(testData);
});
});Database Interactions & Cleanup
When testing APIs that interact with a database, you typically:
- Use a dedicated test database to prevent polluting your development data.
- Clear the database before each test suite or test case (using
beforeEach/afterEachhooks). - Seed data if specific data is needed for a test.
This ensures tests are independent and repeatable.
API Test Scenario
You're testing a Node.js API endpoint /users that accepts POST requests to create a new user. Which of the following statements are TRUE about integration testing this endpoint?
Recap: Integration Testing
Great job! You've learned the fundamentals of integration testing for Node.js API endpoints:
- What it is: Verifying components work together, especially for API requests.
- Tools: Using Supertest with Jest to simulate HTTP requests.
- Method: Sending GET/POST requests and asserting status codes, body content, and data types.
- Best Practices: Considering dedicated test databases for isolation.
This ensures your API is robust and reliable!
คำถามที่พบบ่อย
บทเรียน “การทดสอบการเชื่อมต่อปลายทาง API” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การทดสอบการเชื่อมต่อปลายทาง API” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Node.js Backend Development Bootcamp ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Node.js Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การทดสอบการเชื่อมต่อปลายทาง API”
สร้างการทดสอบการเชื่อมต่อเพื่อตรวจสอบการทำงานร่วมกันระหว่างองค์ประกอบต่าง ๆ และรับรองการทำงานของ API คุณปฏิบัติ Node.js Backend Development Bootcamp ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Node.js Backend Development Bootcamp หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Node.js Backend Development Bootcamp บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “การทดสอบการเชื่อมต่อปลายทาง API” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Node.js Backend Development Bootcamp นี้ได้ไหม
ได้ บทเรียน Node.js Backend Development Bootcamp ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การทดสอบหน่วยด้วย Jest
- การทดสอบการเชื่อมต่อปลายทาง API
- เทคนิคการแก้ไขข้อบกพร่องอย่างมีประสิทธิภาพ
- การจำลองและวัตถุแทนการทดสอบใน Node.js