推荐答案
// www.javascriptcn.com code example
const { test } = require('tap');
const Fastify = require('fastify');
test('should return hello world', async (t) => {
const fastify = Fastify();
fastify.get('/', async (request, reply) => {
return { hello: 'world' };
});
const response = await fastify.inject({
method: 'GET',
url: '/'
});
t.equal(response.statusCode, 200);
t.same(response.json(), { hello: 'world' });
});本题详细解读
1. 引入依赖
首先,我们需要引入 tap 和 fastify 模块。tap 是一个简单的测试框架,而 fastify 是一个高性能的 web 框架。
const { test } = require('tap');
const Fastify = require('fastify');2. 创建测试用例
使用 tap 的 test 方法来定义一个测试用例。test 方法的第一个参数是测试用例的描述,第二个参数是一个异步函数,用于执行测试逻辑。
test('should return hello world', async (t) => {
// 测试逻辑
});3. 创建 Fastify 实例
在测试用例中,我们首先创建一个 Fastify 实例。
const fastify = Fastify();
4. 定义路由
接下来,我们定义一个简单的 GET 路由,该路由返回一个包含 { hello: 'world' } 的 JSON 对象。
fastify.get('/', async (request, reply) => {
return { hello: 'world' };
});5. 发送请求并获取响应
使用 fastify.inject 方法模拟发送一个 GET 请求到根路径 /。inject 方法返回一个 Promise,我们可以使用 await 来等待响应。
const response = await fastify.inject({
method: 'GET',
url: '/'
});6. 断言响应
最后,我们使用 tap 提供的断言方法来验证响应的状态码和内容。
t.equal(response.statusCode, 200);
t.same(response.json(), { hello: 'world' });t.equal用于断言状态码是否为 200。t.same用于断言响应体是否与{ hello: 'world' }相同。
7. 运行测试
将上述代码保存为一个 .js 文件,然后使用 node 命令运行该文件,即可执行测试。
node test.js
通过这种方式,你可以使用 tap 对 Fastify 应用进行单元测试。