API Testing error SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
The test expected JSON but the server sent back an HTML page. The real problem is whatever made the server return HTML, not the parsing.
Published
Why this happens
- The request URL is wrong, so the server or a SPA fallback route returned its HTML 404 or index.html page
- Authentication expired, and the gateway redirected to an HTML login page
- A proxy, WAF, or load balancer returned its own HTML error page (502, 503, a bot challenge) instead of passing the request to the API
- The `Accept` header is missing, so the server content-negotiated its way to HTML
How to fix it
- Log `response.status` and the first few hundred characters of the raw body before parsing, so the failure shows the real page
- Assert on the status code and `content-type` header before calling `.json()`
- Check the base URL and path in the failing environment. A missing `/api` prefix is the classic cause
- Send `Accept: application/json` explicitly
Example
const res = await request.get('/api/orders', {
headers: { Accept: 'application/json' },
});
expect(res.status()).toBe(200);
expect(res.headers()['content-type']).toContain('application/json');
const body = await res.json();