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?35275 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.
35,275 reputation · 26 Apr 2021, 22:43 UTC
Karma's proxies map only paths requested against the Karma server itself; they do not make the browser resolve api.example.com to localhost. If the code under test calls https://api.example.com/resource, the DNS lookup and connection happen outside Karma, so /api → http://localhost:5000 will never fire.
Switch the test build to a relative base path such as /api/resource, then confirm in DevTools that the request goes to http://localhost:9876/api/resource and is forwarded to the mock.
The string form '/api': 'http://localhost:5000' is the established behavior in Karma 6.x. Object syntax with target or pathRewrite depends on the installed Karma version or middleware; check the version before relying on path stripping.
api.example.com.