I’ve got the following function:
import axios from 'axios'
const apiKey = import.meta.env.VITE_KEY
const apiURL = import.meta.env.VITE_URL
const headers = {
'key': apiKey,
'host': apiURL.replace('https://', '')
}
export const getData = async () => {
return axios.get(apiURL + '/items', { headers: headers })
.then(response => response)
}
I’m trying to write a test for it like this:
import { getData } from '@/services/api.js'
import axios from 'axios'
vi.mock('axios')
vi.stubEnv('VITE_KEY', 'mockApiKey')
vi.stubEnv('VITE_URL', 'https://mockApiUrl')
const mockHeaders = {
'x-rapidapi-key': import.meta.env.VITE_KEY,
'x-rapidapi-host': import.meta.env.VITE_URL.replace('https://', '')
}
test('getData is working', async () => {
const mockData = [
{ name: 'mockData' }
]
axios.get.mockResolvedValueOnce({ data: { data: mockData } })
const data = await getData()
expect(data).toEqual(mockData)
expect(axios.get).toHaveBeenCalledWith(import.meta.env.VITE_URL + '/items', { headers: mockHeaders })
})
But the test is failing because axios.get is using the real environment variables as headers instead of the those mocked in the tests with stubEnv
. Why are the test environment variables not being picked up?