Home >Web Front-end >JS Tutorial >Back-End Testing
1. Introduction to Back-End Testing
2. Setting Up the Environment
Step-by-step instructions to set up a new Node.js project:
mkdir backend-testing cd backend-testing npm init -y npm install express mocha chai supertest --save-dev
Explanation of the installed packages:
3. Creating a Simple API with Express
Example code for a basic Express server with a few endpoints:
// server.js const express = require('express'); const app = express(); app.get('/api/hello', (req, res) => { res.status(200).json({ message: 'Hello, world!' }); }); app.listen(3000, () => { console.log('Server is running on port 3000'); }); module.exports = app;
Explanation of the API structure and endpoints.
4. Writing Your First Test with Mocha and Chai
Creating the test directory and a basic test file:
mkdir test touch test/test.js
Writing a simple test:
// test/test.js const request = require('supertest'); const app = require('../server'); const chai = require('chai'); const expect = chai.expect; describe('GET /api/hello', () => { it('should return a 200 status and a message', (done) => { request(app) .get('/api/hello') .end((err, res) => { expect(res.status).to.equal(200); expect(res.body).to.have.property('message', 'Hello, world!'); done(); }); }); });
Explanation of the test code:
5. Running the Tests
How to run the tests using Mocha:
npx mocha
Interpreting the test results.
6. Additional Test Cases
Example:
describe('GET /api/unknown', () => { it('should return a 404 status', (done) => { request(app) .get('/api/unknown') .end((err, res) => { expect(res.status).to.equal(404); done(); }); }); });
7. Best Practices for Back-End Testing
8. Conclusion
9. Additional Resources
10. Call to Action
The above is the detailed content of Back-End Testing. For more information, please follow other related articles on the PHP Chinese website!