Angular HTTP Testing “SyntaxError: Unexpected token o in JSON at position 1”

tl:dr; Solve this Issue:

Add the following line to your imports:

 

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.

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:

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.

 


Can Kattwinkel

Entwickler bei thecodecampus

Leave a Reply

Your email address will not be published. Required fields are marked *