我正在使用筋膜-cli构建我的服务器应用程序。
对于测试,我想生成一些测试JWT。因此,我想使用sign方法的fastify-jwt插件。
如果我使用fastify start -l info ./src/app.js运行应用程序,一切都可以按预期工作,并且可以访问装饰器。
但是在测试设置中,我得到了一个错误,即jwt装饰器是未定义的。似乎装潢工没有暴露出来,我只是找不到任何错误。对于测试,我在以下命令中使用节点抽头:tap \"test/**/*.test.js\" --reporter=list
app.js
import { dirname, join } from 'path'
import autoload from '@fastify/autoload'
import { fileURLToPath } from 'url'
import jwt from '@fastify/jwt'
export const options = {
ignoreTrailingSlash: true,
logger: true
}
export default async (fastify, opts) => {
await fastify.register(jwt, {
secret: process.env.JWT_SECRET
})
// autoload plugins and routes
await fastify.register(autoload, {
dir: join(dirname(fileURLToPath(import.meta.url)), 'plugins'),
options: Object.assign({}, opts),
forceESM: true,
})
await fastify.register(autoload, {
dir: join(dirname(fileURLToPath(import.meta.url)), 'routes'),
options: Object.assign({}, opts),
forceESM: true
})
}helper.js
import { fileURLToPath } from 'url'
import helper from 'fastify-cli/helper.js'
import path from 'path'
// config for testing
export const config = () => {
return {}
}
export const build = async (t) => {
const argv = [
path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'src', 'app.js')
]
const app = await helper.build(argv, config())
t.teardown(app.close.bind(app))
return app
}root.test.js
import { auth, build } from '../helper.js'
import { test } from 'tap'
test('requests the "/" route', async t => {
t.plan(1)
const app = await build(t)
const token = app.jwt.sign({ ... }) //-> jwt is undefined
const res = await app.inject({
method: 'GET',
url: '/'
})
t.equal(res.statusCode, 200, 'returns a status code of 200')
})发布于 2022-10-13 18:17:10
问题是您的应用程序关系图如下所示:

当您编写const app = await build(t)时,app变量指向Root Context,但是Your app.js包含jwt装饰符。
要解决这个问题,只需将app.js文件与fastify-plugin包装在一起,因为它破坏了封装:
import fp from 'fastify-plugin'
export default fp(async (fastify, opts) => { ... })注意:您可以通过使用fastify-overview (和fastify-overview-ui插件一起)来可视化这个结构:

https://stackoverflow.com/questions/74057840
复制相似问题