问题描述
可以在端口上启动服务器并使用库“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