Setting baseURL in default configuration
Problem
In some cases my app requires different defaults from the standard ones, and I've been dealing with this by putting something like this in the app's entry point: [code block] My tests are run in Node and I want to override the `baseURL` so that axios will work with Nock even with relative URLs, but the code above doesn't work. Would it be reasonable to add this parameter to the defaultConfig when instantiating Axios? Or is there a better way I should be doing this? I have an example of what I mean here.
Unverified for your environment
Select your OS to check compatibility.
1 Fix
Override baseURL in Axios Default Configuration
The issue arises because the default Axios configuration does not allow for dynamic changes to the `baseURL` after instantiation, which is necessary for testing environments where Nock is used to mock HTTP requests. This leads to failures when relative URLs are used without a proper base URL.
Awaiting Verification
Be the first to verify this fix
- 1
Install Axios and Nock
Ensure that both Axios and Nock are installed in your project to handle HTTP requests and mocking respectively.
bashnpm install axios nock - 2
Create a Custom Axios Instance
Instead of using the default Axios instance, create a custom instance where you can set the `baseURL` dynamically based on your environment (e.g., testing).
javascriptconst axios = require('axios'); const axiosInstance = axios.create({ baseURL: process.env.BASE_URL || 'http://localhost' }); - 3
Set BASE_URL in Test Environment
Before running your tests, set the `BASE_URL` environment variable to the desired base URL that Nock will intercept. This allows you to use relative URLs in your Axios requests.
bashexport BASE_URL=http://mockapi.com - 4
Use Custom Axios Instance in Tests
Replace all instances of the default Axios calls in your tests with the custom instance you created. This ensures that the overridden `baseURL` is used.
javascriptconst response = await axiosInstance.get('/endpoint'); - 5
Run Tests and Verify
Execute your tests to ensure that they pass with the new configuration. Check that Nock is intercepting the requests correctly and that the responses are as expected.
bashnpm test
Validation
Confirm that all tests pass without errors related to Axios requests. Additionally, verify that the requests are being intercepted by Nock and that the correct responses are returned.
Sign in to verify this fix
Environment
Submitted by
Alex Chen
2450 rep