推荐答案
// www.javascriptcn.com code example
const request = require('supertest');
const express = require('express');
const app = express();
app.get('/user', function(req, res) {
res.status(200).json({ name: 'John' });
});
describe('GET /user', function() {
it('responds with json', function(done) {
request(app)
.get('/user')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200, { name: 'John' }, done);
});
});本题详细解读
1. 安装 supertest
首先,你需要安装 supertest 和 express 模块。可以通过以下命令进行安装:
npm install supertest express --save-dev
2. 创建 Express 应用
在测试文件中,首先需要创建一个 Express 应用实例。这个应用实例将用于模拟 API 请求。
const express = require('express');
const app = express();3. 定义路由
在 Express 应用中定义你要测试的路由。例如,定义一个简单的 GET 路由:
app.get('/user', function(req, res) {
res.status(200).json({ name: 'John' });
});4. 使用 supertest 进行测试
使用 supertest 来模拟请求并验证响应。supertest 提供了一个链式 API,可以方便地设置请求头、期望的响应状态码、响应内容等。
// www.javascriptcn.com code example
const request = require('supertest');
describe('GET /user', function() {
it('responds with json', function(done) {
request(app)
.get('/user')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200, { name: 'John' }, done);
});
});5. 运行测试
最后,使用测试框架(如 Mocha 或 Jest)来运行测试。如果所有期望都满足,测试将通过。
mocha test.js
通过以上步骤,你可以在 Express 应用中使用 supertest 进行 API 测试,确保你的 API 行为符合预期。