Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Override runtimeConfig in vitest.config.ts file doesn't seem to work #833

Closed
vctrtvfrrr opened this issue Apr 29, 2024 · 3 comments
Closed
Labels

Comments

@vctrtvfrrr
Copy link

Environment

Reproduction

https://github.com/vctrtvfrrr/hinario-reformado

Describe the bug

I can't test the Nuxt3 server endpoints. I'm using vitest and @nuxt/test-utils to make API calls, but I haven't even been able to override the Nuxt runtime settings:

// vitest.config.ts
import { defineVitestConfig } from '@nuxt/test-utils/config'

export default defineVitestConfig({
  test: {
    environment: 'nuxt',
    globals: true,
    environmentOptions: {
      nuxt: {
        overrides: {
          runtimeConfig: {
            database: ':memory:', // Must overwrite the /path/to/db.sqlite defined into nuxt.config.ts
          },
        },
      },
    },
  },
})
// server/utils/db.ts
export function useDb() {
  const config = useRuntimeConfig()
  const sqlite = new Database(config.database)
  return drizzle(sqlite, {...})
}
// server/api/articles.post.ts
export default defineEventHandler(async (event) => {
  const newArticleData = await readBody<NewArticle>(event)
  const [article] = await useDb().insert(articlesTable).values(newArticleData).returning()
  return article
})
// articles.post.spec.ts
import { $fetch, setup } from '@nuxt/test-utils/e2e'

describe('Article Routes', async () => {
  await setup()

  test('POST /api/articles', async () => {
    const response = await $fetch('/api/articles', { method: 'POST', body: {...} })
    expect(response).toContain('...')
  })
})

Nuxt's official documentation doesn't cover server testing very well and Nitro/H3 doesn't even have testing documentation.

Additional context

No response

Logs

No response

Copy link

dosubot bot commented Apr 29, 2024

To address the issue of overriding runtimeConfig in your vitest.config.ts for Nuxt3 server endpoint testing, ensure your configuration in vitest.config.ts correctly specifies the overrides. Here's a refined approach:

  1. Correctly Apply Overrides: In your vitest.config.ts, ensure you're using the overrides option to specify your custom configuration. This should directly target the settings you wish to modify for your tests, such as the database connection string.
import { defineVitestConfig } from '@nuxt/test-utils/config';

export default defineVitestConfig({
  test: {
    environment: 'nuxt',
    globals: true,
    environmentOptions: {
      nuxt: {
        overrides: {
          runtimeConfig: {
            publicRuntimeConfig: {
              databaseUrl: 'your_in-memory_database_connection_string',
            },
          },
        },
      },
    },
  },
});
  1. Utilize Environment Variables for Flexibility: Consider using environment variables for database configuration to easily switch between different environments (development, testing, production). You can specify a .env.test file for your test environment.
export default defineVitestConfig({
  test: {
    environmentOptions: {
      nuxt: {
        dotenv: {
          fileName: '.env.test',
        },
        overrides: {
          // Your overrides here
        },
      },
    },
  },
});
  1. Mock useRuntimeConfig in Tests: For more granular control in tests, you can mock the useRuntimeConfig composable function directly in your test files using mockNuxtImport from @nuxt/test-utils/runtime. This allows you to define runtime configurations specifically for each test case.

By ensuring your vitest.config.ts is correctly set up to apply these overrides, you can effectively isolate your test environment and use an in-memory database or a specific test database, avoiding interference with your production or development environments.

Details

Sources


About Dosu
This response is meant to be useful and save you time. It is not meant to be a precise solution, but rather a starting point for your own research.

Help me be more useful! Please leave a 👍 if this is helpful and 👎 if it is irrelevant.

To continue the conversation, mention @dosu.

@dosubot dosubot bot added bug Something isn't working vitest-environment labels Apr 29, 2024
@FabianClemenz
Copy link

Sorry for writing on this issue @ricardogobbosouza

I have an error where the test utils not getting my custom env vars. I tried overrwriting using the overwrite config and i tried using the dotenv config but my tests still use the existing .env file.

I created an plugin for my api like mentioned here https://nuxt.com/docs/guide/recipes/custom-usefetch setting the baseURL as follows

const config: RuntimeConfig = useRuntimeConfig();
const api = $fetch.create({
    baseURL: config.public.apiBase,

So my tests are always trying to run against the apiBase coming from .env file. No chance for overwriting this (before, when i used $fetch directly it worked)

@danielroe
Copy link
Member

danielroe commented Feb 21, 2025

The nuxt environment in the config is a purely client-side one (and also does not affect the e2e test at all).

You can track #531 for server environment support, if you're looking for a vitest runtime environment.

Alternatively, you can override runtimeConfig when running your e2e setup by passing it as an override to the setup function from @nuxt/test-utils/e2e

Note that I couldn't see any example of the kind of test you're trying to do in your linked reproduction.

@danielroe danielroe closed this as not planned Won't fix, can't repro, duplicate, stale Feb 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants