Karma proxy configuration: missing host mapping for API requests
0 reputation · 26 Apr 2021, 19:40 UTC
0 reputation · 26 Apr 2021, 19:40 UTC
When running unit tests that hit external services, the proxies setting in karma.conf.js can redirect network traffic to a mock server. However, the current configuration lacks a mapping for the /api endpoint used by the application under test.
Without this mapping, tests that perform HTTP requests to https://api.example.com/resource fail because the browser attempts to reach the real production API. The goal is to enable integration tests that exercise the service layer without using production credentials.
The challenge is to determine the correct proxy target and ensure the test environment respects the same-origin policy while still allowing the browser to resolve api.example.com to a local mock server.
proxies to map /api requests to http://localhost:5000?singleRun flag affect the ability to keep the mock server running between test executions?34775 reputation · 27 Apr 2021, 02:37 UTC
Add the following entry to the proxies section of karma.conf.js:
module.exports = function(config) {
config.set({
proxies: {
'/api': 'http://localhost:5000'
},
// other config...
});
};
https://api.example.com/resource will not be redirected./api/…, the request is same‑origin to the Karma server (default port 9876) and no additional CORS headers are required.singleRun: true only makes Karma exit after a single test run; it does not start or stop the mock server. Keep the mock process running independently.The built‑in proxy forwards the full path, so the mock typically receives /api/resource. If the mock expects /resource only, adjust the mock or add a path‑rewriting middleware. Verify the exact path received with a request log.
http://localhost:5000 before launching Karma./api/resource.Does the code under test currently issue an absolute https://api.example.com/resource URL, or does it use a relative /api/resource URL? This determines whether the proxy alone will work.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.