Reputation: 21
I am using Mock Service Worker (MSW), in my Vite React app which is working fine when the handler paths were hardcoded and my handler URL matched my fetch URL.
But as the project is progressing, we now have different APIs for development and QA/Staging.
We are using Environment variables for our API URLs, and things are working with fetching the data. But our tests fail when mocking, which I think is caused by the use of environment variables.
Here is an example of one of the endpoints for the API.
export const USER_URL = `${import.meta.env.VITE_API_URL_USER}/api/v1/userroles`;
When we import this, and use this to make a fetch request, everything is working as intended. And confirmed using the Network tab in the browser that the correct URL is being used in development.
Here is the handler, for MSW but the mocked API unit test always seems to fail.
If I hard code the URL for both the handler and fetch, its works fine, but we need the URL in the component to be dynamic, so it uses the correct API endpoint in staging/QA
// User Roles
rest.get(USER_URL, (req, res, ctx) => {
return res(
ctx.json([
{
firstName: 'Admin',
lastName: 'Admin',
fullName: 'Admin Admin',
}
])
);
})
Here is the unit test that fails, render template is being used, as to avoid having to re-write the providers, which is all written outside the describe function.
it('should show the fullname of the user after api data has been loaded', async () => {
render(renderTemplate);
const heading = await screen.findByText('Admin Admin');
expect(heading).toBeInTheDocument();
});
I hardcoded the values initially to make the handler and unit test worked and MSW was set up correctly as I followed the documentation. This was working fine.
I kept a hardcoded path in the handler, and updated the fetch URL to use to dynamic value, and this failed the test.
I am not sure how to proceed with this test and would love to learn how to work with environment variables and testing.
Upvotes: 1
Views: 1947
Reputation: 165
I had a very similar issue with vitest and I solved it mocking the env variables. Vitest allow to mock env varibales using vi.stubEnv
but it didn't work for me because it seems like msw was setting the handlers just before the env variable was mocked, and I couldn't set it to do it after the envs mock.
So I found a different approach from here and it was:
const {
VITE_APP_BACKEND_URL
} = import.meta.env;
export {
VITE_APP_BACKEND_URL
};
In my code I am using axios
import { VITE_APP_BACKEND_URL } from 'src/env';
const axiosInstance = axios.create({
baseURL: VITE_APP_BACKEND_URL,
headers: {
'Content-Type': 'application/json',
},
});
The handlers
import { VITE_APP_BACKEND_URL } from 'src/env';
export const testHandler = [
http.get(`${VITE_APP_BACKEND_URL}/my-endpoint`, () => {
return HttpResponse.json(myResponseMock);
}),
];
vi.mock('src/env', () => ({
VITE_APP_BACKEND_URL: 'TestBackendURL.com',
}));
Upvotes: 0