nuxt / test-utils

๐Ÿงช Test utilities for Nuxt
http://nuxt.com/docs/getting-started/testing
MIT License
287 stars 74 forks source link

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

Open vctrtvfrrr opened 2 months ago

vctrtvfrrr commented 2 months ago

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

dosubot[bot] commented 2 months ago

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** - [src/config.ts](https://github.com/nuxt/test-utils/blob/main/src/config.ts) - [CHANGELOG.md](https://github.com/nuxt/test-utils/blob/main/CHANGELOG.md) - [package.json](https://github.com/nuxt/test-utils/blob/main/package.json) - [examples/app-vitest-full/tests/nuxt/mock-nuxt-composable-1.spec.ts](https://github.com/nuxt/test-utils/blob/main/examples/app-vitest-full/tests/nuxt/mock-nuxt-composable-1.spec.ts)
**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.