nuxt / test-utils

🧪 Test utilities for Nuxt
http://nuxt.com/docs/getting-started/testing
MIT License
313 stars 81 forks source link

Can't fetch within beforeAll() or afterAll() #801

Closed MickL closed 6 months ago

MickL commented 6 months ago

Environment

------------------------------
- Operating System: Darwin
- Node Version:     v21.6.1
- Nuxt Version:     3.11.1
- CLI Version:      3.11.1
- Nitro Version:    2.9.4
- Package Manager:  bun@1.0.33
- Builder:          -
- User Config:      devtools, modules, runtimeConfig, image, nitro, security
- Runtime Modules:  @nuxt/image@1.4.0, @nuxtjs/i18n@8.2.0, @pinia/nuxt@^0.5.1, @vueuse/nuxt@10.9.0, nuxt-security@^1.2.1, @nuxt/test-utils/module@^3.12.0
- Build Modules:    -
------------------------------

Reproduction

https://stackblitz.com/edit/github-krtpdn-tvzxcc?file=test%2Fsomething.spec.ts

Describe the bug

Within beforeAll() and afterAll() I cant use fetch or $fetch.

Error in beforeAll():

Error: url is not available (is server option enabled?)

Error in afterAll():

Cannot set property request of FetchError: [GET] "http://127.0.0.1:54554/api/other": fetch failed which has only a getter

Additional context

It is crucial to test server endpoints to do some work within beforeAll and afterAll, e.g. prepare the database by creating some items and in the end cleaning everything up again.

Logs

No response

danielroe commented 6 months ago

You won't be able to fetch from your Nuxt app because it is initialised in beforeAll, and torn down in afterAll. But you can fetch from other places, just not using the $fetch from @nuxt/test-utils/e2e, which is only for getting data from a running Nuxt server. You, could, for example, import { $fetch as externalFetch } from 'ofetch' and that should work fine anywhere in your test suite.