如何在不启动服务器的情况下编写 api 请求测试?

问题描述

可以在端口上启动服务器并使用库“supertest”对其进行测试。 我想知道是否可以在不运行服务器的情况下执行相同操作?

Express 应用程序,与 fastify 应用程序或其他应用程序相同,从引擎盖下的本机节点获取请求和响应参数,如下所示:

const server = http.createServer((req,res) => {
  res.end('hello\n');
});

因此应该可以直接从测试中调用该回调。 如何获得该回调?是否有任何工具包可以帮助构建回调的请求和响应对象?

原因 - 只是为了使测试更快。由于我不想测试 HTTP 协议和 node 内部,我想跳过它以节省时间。

解决方法

Fastify 有 this feature out of the box

'use strict'

const { test } = require('tap')
const Fastify = require('fastify')

test('requests the "/" route',async t => {
  const fastify = Fastify()

  fastify.get('/',function (request,reply) {
    reply.send({ hello: 'world' })
  })

  const response = await app.inject({
    method: 'GET',url: '/'
  })
  t.strictEqual(response.statusCode,200,'returns a status code of 200')
})

为了 moch req/resp 对象,它在引擎盖下使用了 light-my-request

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...