August 14, 2017
Angular HTTP Testing “SyntaxError: Unexpected token o in JSON at position 1”
tl:dr; Solve this Issue:
Add the following line to your imports:
1 |
import { Response } from '@angular/http'; |
Full version:
A common problem affecting many developers when writing tests for the Angular 4 HTTP service is the following stack trace. It occurs if you assemble an response using a the wrong class. The call of .json()
will throw the error.
1 |
"Unexpected token o in JSON at position 1" |
1 |
"SyntaxError: Unexpected token o in JSON at position 1 at SafeSubscriber._next (http://localhost:9876/_karma_webpack_/webpack: [...] |
It throws because the response is of a false type and the body of the response is of type ReadableStream
instead of a string value that contains your JSON.
Your source code might look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
... const mockResponse = { data: [ { id: 2313, value: 'Value for 2313' }, { id: 1231, value: 'Value for 1231' }, ] }; mockBackend.connections.subscribe((connection) => { connection.mockRespond(new Response(new ResponseOptions({ body: JSON.stringify(mockResponse) }))); }); ... |
The actual problem is not in the code but in the class imported for Response
. By default the import will point to lib.es6.d.ts file. Since it is usually available as global ambient there is no explicit import necessary. Therefore we have to overwrite it to import response correctly from @angular/http
.
1 |
import { Response } from '@angular/http'; |
You saved my day! Thanks for sharing!
Thank you!