📜  supertest 示例 - Shell-Bash (1)

📅  最后修改于: 2023-12-03 15:35:11.378000             🧑  作者: Mango

Supertest 示例 - Shell-Bash

Supertest 是一个 HTTP 服务测试库,它的目标是使得测试 HTTP 服务变得简单、快速和准确。它在 Node.js 中运行,并提供了一个 DSL(领域专用语言)来构建 HTTP 请求,并使用断言语法来验证响应排列。

安装 Supertest

安装 Supertest 很简单,只需要使用 npm 命令即可:

npm install supertest --save-dev
使用 Supertest

下面是一个使用 Supertest 进行 HTTP 请求测试的示例:

const request = require('supertest');
const app = require('../app');

describe('Test HTTP server', function() {
  it('responds to /api/getData with JSON', function(done) {
    request(app)
      .get('/api/getData')
      .set('Accept', 'application/json')
      .expect('Content-Type', /json/)
      .expect(200)
      .end(function(err, res) {
        if (err) return done(err);
        done();
      });
  });
});

上面的示例中:

  • request 方法创建一个测试请求,并传入 Express.js 应用程序。
  • get 方法指定请求的 HTTP 方法和 URI。
  • set 方法设置请求头。
  • expect 方法设置响应的头信息或状态码。
  • end 方法用于提交 HTTP 请求,并验证响应结果。
Supertest 断言语法

Supertest 提供以下的断言语法:

expect(status[, fn])

指定 HTTP 响应的状态码。例如:

it('responds with a 200 status code', function(done) {
  request(app)
    .get('/')
    .expect(200, done);
});
expect(header, value[, fn])

指定 HTTP 响应头信息。例如:

it('responds with an "application/json" content type', function(done) {
  request(app)
    .get('/api')
    .set('Accept', 'application/json')
    .expect('Content-Type', /json/)
    .expect(200, done);
});
expect(body[, fn])

指定 HTTP 响应体。例如:

it('responds with a body', function(done) {
  request(app)
    .get('/')
    .expect('Hello, World!', done);
});
结束语

通过本文的介绍,你可以学习到 Supertest 的安装和使用方法,并且了解了 Supertest 的断言语法。希望这篇文章能对你在测试 HTTP 服务方面的工作有所帮助。