I have a service that is pretty much a wrapper to call an API using useFetch
composable.
export default async () => {
const config = useRuntimeConfig().public
const { data, error } = await useFetch(
`${config.BASE_API}/${config.MOVIES}`,
{
transform: (res: Movie[]) => {
return res.slice(0, 10)
}
}
)
if (error.value) {
throw createError({
...error.value,
statusMessage: `Não foi possível obter a lista de filmes`
})
}
return data.value ?? []
}
I’m still newbie on tests and I was trying to create a test for this service.
import { describe, it, expect } from 'vitest'
import getMovies from '~/utils/services/movies/getMovies'
import { mockNuxtImport } from '@nuxt/test-utils/runtime'
import type { Movie } from '~/types/Movie'
mockNuxtImport('useRuntimeConfig', () => {
return () => {
return {
public: {
BASE_API: 'https://dummyapi.online/api',
MOVIES: '/movies'
}
}
}
})
describe('useClientInfo', () => {
it('should return an array of movies', async () => {
const data: Movie[] = await getMovies() //ERROR 500
.then((res) => {
expect(Array.isArray(res)).toBe(true)
return res
})
.catch((err) => {
return []
})
expect(data.length).toBeGreaterThan(0)
})
})
On the page everything goes ok, but I receive a 500 error when testing.
I was in the docs and I believe my problem is something related to this note, on the registered endpoint section.
Note: If your requests in a component go to an external API, you can use baseURL and then make it empty using Nuxt Environment Override Config ($test) so all your requests will go to Nitro server.
But for me is not clear what I really should do.
I added this to my nuxt.config
$test: {
app: {
baseURL: ''
}
}
And I can confirm that the test is using the variable defined into mockNuxtImport
, but still get the 500 error.
I’m not sure what I’m missing here.
I’ll be very glad if anyone can point me the right direction.
Thanks in advance!