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

How to fix it

  1. Log `response.status` and the first few hundred characters of the raw body before parsing, so the failure shows the real page
  2. Assert on the status code and `content-type` header before calling `.json()`
  3. Check the base URL and path in the failing environment. A missing `/api` prefix is the classic cause
  4. 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();