Combining Vitest with FastifyAutoload resulted in a FastifyError: The plugin provided must either be a function or a promise, but instead, an 'object' was received

My application built on Fastify (

"fastify": "^4.26.0"
) operates smoothly under normal conditions with no issues. However, when trying to incorporate unit testing using Vitest, every test fails despite their simplicity. Upon troubleshooting, I found that by commenting out certain lines in my app.ts file, the tests 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),
  })

Seeking a solution, I stumbled upon this GitHub issue. Though not identical to my problem, it pointed me towards a temporary workaround. I configured my vitest.config.mts file as follows:

import { defineConfig } from 'vitest/config'

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

This setup allowed me to run tests without any trouble for several months. However, I am now stuck as I am consistently facing this 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

Answer №1

It's important to avoid placing any non-plugin files inside the plugins folder when using autoload. This could cause Vitest to malfunction.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Make a decision on whether to use a Typescript type or interface based on an external

My goal is to select a TS interface or type based on an external condition rather than the input. This external condition could be a feature toggle, for example. Allow me to elaborate: type NotEmptyName = string; type EmptyableName = string | null; cons ...

One method for deducing types by analyzing the function's return value within a react prop

There is a component definition that accepts two generics: function AsyncFlatList<ApiResponse, Item>({}: { url: string; transformResponse: (response: ApiResponse) => Item[]; keyExtractor: (item: Item) => string; }) { // the implementati ...

Steps for integrating Cordova-vk plugin into an Ionic 3 project

I am looking to incorporate the cordova-vk plugin into my app, but I am having trouble connecting it to Typescript. vkSdk is not defined I understand that the plugin is located in the node_modules folder. How can I successfully integrate it into my page ...

Error notifications continue to appear despite the presence of data in the input field

I am utilizing a component to exhibit various information (such as first name, last name, phone number, etc.) fetched from the API. The main focus is on executing CRUD operations, particularly the update operation. Referencing the image below: https://i ...

Only perform a simulated side effect a limited number of times

I am working on testing a celery retry task that is designed to keep retrying until successful. By using mock's side_effect feature, I can simulate failures for a certain number of executions and then set it to None to clear the side effect. However, ...

Error: The function visitor.visitUnaryOperatorExpr is not defined as a function

I recently started developing an Angular app with a purchased template and collaborating with another developer. Initially, I was able to successfully build the project for production using ng build --prod. However, when trying to build it again yesterday, ...

Retrieving the selected date from mat-datepicker into a FormControl

When creating a POST request to an API, I encountered an issue with the mat-datepicker field as it throws an error when inside the ngOnInit() call (since nothing is selected yet). Other fields like name, email, etc. work fine, but extracting a value from t ...

Divide the list of commitments into separate groups. Carry out all commitments within each group simultaneously, and proceed to the next group

My Web Crawling Process: I navigate the web by creating promises from a list of website links. These promises act as crawlers and are executed sequentially. For instance, if I have 10 links, I will crawl the first link, wait for it to complete, then move ...

classes_1.Individual is not a callable

I am facing some difficulties with imports and exports in my self-made TypeScript project. Within the "classes" folder, I have individual files for each class that export them. To simplify usage in code, I created an "index.ts" file that imports all class ...

How can I set a document ID as a variable in Firebase Firestore?

I recently set up a firestore collection and successfully added data (documents) to it. Firestore conveniently generates unique document ids for each entry. Inserting Data this.afs.collection('questions').add({ 'question': message, &a ...

Is there a way to retrieve a particular object from a versatile function?

Here is a generic function to consider: public getData<T>(url: string): Observable<T> { return this.httpClient.get<T>(url); } I am looking for a way to test this function by returning a mock object array, especially if the remote ...

In need of secure HTML, received a dose of Style instead

I am currently developing a component that loads html content dynamically and validates the loaded styles to prevent any mixing of app styles with the dynamic template's styles. This is the structure of my HTML component: <div class="modal-header ...

Tips for storing an array of ReplaySubjects in a single variable in an Angular application

I am looking to store several ReplaySubjects in a single array. Here is my code: public filteredSearch: ReplaySubject<any[]> = new ReplaySubject(1); this.filteredSearch[id].next(filter(somedata)); When I run this code, I encounter an error saying ...

Automatically insert a hyphen (-) between each set of 10 digits in a phone number as it is being typed into the text

I'm attempting to automatically insert a hyphen (-) in between 10 digits of a phone number as it is being typed into the text field, following North American standard formatting. I want the output to look like this: 647-364-3975 I am using the keyup ...

Function with a TypeScript Union Type

I'm attempting to define a property that can be either a lambda function or a string in TypeScript. class TestClass { name: string | () => string; } You can find a sample of non-working code on the TS playground here. However, when compiling ...

The Interface in TypeScript will not function properly when used on a variable (Object) that has been declared with the value returned from a function

I am currently in the process of developing an application using Ionic v3. Strangely, I am encountering issues with my interface when trying to assign a variable value returned by a function. Here is an example that works without any problems: export int ...

Enhance your coding experience with TypeScript's autocomplete in Visual Studio Code

After migrating a project from JavaScript to TypeScript, I am not seeing autocomplete suggestions or type hints when hovering over variables in Visual Studio Code editor (Version 1.7.2). Even the basic example provided below does not display any auto-com ...

Encountering TS2304 error message while running TypeScript files indicates the inability to locate the name 'PropertyKey', in addition to another error - TS2339

I encountered an issue while attempting to execute a spec.ts file in the Jasmine Framework. After installing @types/core-js version 0.9.46 using the command npm i @types/core-js, I started receiving the following error messages: > ../../node_modules/ ...

TypeScript's attempt to replicate Scala's underscore feature has been implemented, but it proves to

I've been working on a personal project for the past 2 years trying to implement Scala's underscore in TypeScript, but haven't been successful. Here is my attempted implementation and its effect. The only thing that I really care about typi ...

Tips for preloading a TypeScript class using the -r option of ts-node

Imagine you have a file called lib.ts that contains the following code: export class A {} console.log('script loaded'); Now, if you launch the ts-node REPL using the command: npx ts-node -r ./lib.ts, you will see that it outputs "script loaded," ...