Search code examples
typescriptunit-testingfastifyvitest

Vitest + FastifyAutoload = FastifyError: Plugin must be a function or a promise. Received: 'object'


I have an application running on Fastify ("fastify": "^4.26.0"), which operates flawlessly under normal conditions, presenting no issues whatsoever. However, when attempting to implement unit testing with Vitest, I encounter a persistent problem where every test fails, regardless of its simplicity. In the process of troubleshooting, I discovered that commenting out the following lines in my app.ts file allows the tests to run successfully:

  // This loads all plugins defined in plugins
  // those should be support plugins that are reused
  // through your application
  void app.register(AutoLoad, {
    dir: join(__dirname, 'plugins'),
    options: Object.assign({}, opts),
  })

In search of a solution, I came across this issue on GitHub, which, although not exactly the same as my issue, led me to a temporary workaround. I managed to implement the following configuration in my vitest.config.mts file:

import { defineConfig } from 'vitest/config'

export default defineConfig({
    test: {
        include: ["test/**/*.test.ts"],
        silent: false,
        server: {
            deps: {
                inline: ["@fastify/autoload"],
            },
        },
    },
});

With this setup, I was able to run the tests without any issues for a few months. However, I am now unable to get the tests running again, consistently encountering the following error:

 FAIL  test/main.test.ts > App > should start the app
 FastifyError: Plugin must be a function or a promise. Received: 'object'
 ❯ validatePlugin node_modules/avvio/lib/validate-plugin.js:19:13
 ❯ Boot._addPlugin node_modules/avvio/boot.js:166:3
 ❯ Boot.use node_modules/avvio/boot.js:139:25
 ❯ Object.server.<computed> [as register] node_modules/avvio/boot.js:204:14
 ❯ registerPlugin node_modules/@fastify/autoload/index.js:342:11
    340|   }
    341| 
    342|   fastify.register(plugin, options)
       |           ^
    343| 
    344|   meta.registered = true
 ❯ registerAllPlugins node_modules/@fastify/autoload/index.js:112:19
 ❯ autoload node_modules/@fastify/autoload/index.js:92:7

Solution

  • When using autoload, you should never have a non-plugin file inside the plugins folder loaded by autoload. Vitest will not work if that happens.