Unit testing error: "Unprepared (in promise) SyntaxError: Unexpected token o in JSON at position 1"

I would like a unit test service, however when I run the test I get the following error:

Unprepared (in promise) SyntaxError: Unexpected o token in JSON at position 1 in MapSubscriber.project (auth.service.ts: 217) in MapSubscriber.Array.concat.MapSubscriber._next (map.js: 77) in MapSubscriber.Array. concat.Subscriber.next (Subscriber.js: 89) at TakeSubscriber.Array.concat.TakeSubscriber._next (take.js: 80) at TakeSubscriber.Array.concat.Subscriber.next (Subscriber.js: 89) in ReplaySubject.Array .concat.ReplaySubject._subscribe (ReplaySubject.js: 55) in ReplaySubject.Array.concat.Observable._trySubscribe (Observable.js: 57) in ReplaySubject.Array.concat.Subject._trySubscribe (Subject.js: 97) in Replay Array.concat.Observable.subscribe (Observable.js: 45) at TakeOperator.Array.concat.TakeOperator.call (take.js: 60) at AnonymousSubject.Array.concat.Observable.subscribe (Observable.js:42) in MapOperator.Array.concat.MapOperator.call (map.js: 54) in AnonymousSubject.Array.concat.Observable.subscribe (Observable.js: 42) in CatchOperator.Array.concat.CatchOperator.call (catch.js : 79) in AnonymousSubject.Array.concat.Observable.subscribe (Observable.js: 42)

The corresponding line ( auth.service.ts:217) is highlighted below in the code. Running the application works fine, so I don't see the obvious reason why the test fails.

NB: This SO post assumes I am parsing an object twice. But shouldn't this work when starting the application too?

auth.service.ts

public login(username: string, password: string): Observable<User> {
    // ...

    return this.http.request(path, requestOptions).map((response: Response) => {
        if (response.status === 200) {
          const token = response.json().token; // <<-- Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1

          const user = this.extractUser(response);
          return user;
        }

        return null;
      })
      .catch(this.handleError);
  }

auth.service.spec.ts

describe('AuthService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        AuthService,
        MockBackend,
        BaseRequestOptions,
        {
          provide: Http,
          useFactory: (backend: MockBackend, options: BaseRequestOptions) => new Http(backend, options),
          deps: [MockBackend, BaseRequestOptions]
        }
      ],
      imports: [
        RouterTestingModule
      ],
    });
  });

  it('should return an Observable<User>', inject([AuthService, MockBackend], (authService: AuthService, mockBackend: MockBackend) => {
    mockBackend.connections.subscribe((connection: any) => {
      connection.mockRespond(new Response(new ResponseOptions({
        body: '{"token": "abc123", "name":"Jeff"}'
      })));
    });

    authService.login('jeff@example.com', 'password').subscribe(user => {
      expect(user.name).toEqual('Jeff');
    });
  }));

});

When registering a response, the following is issued:

Response
  body: ReadableStream
    locked: true
    __proto__: Object
  bodyUsed: true
  headers: Headers
    __proto__: Headers
  ok: true
  redirected: false
  status: 200
  statusText: "OK"
  type: "default"
  url: ""
    __proto__: Response
+6
source share
4 answers

The error Unexpected token ... in JSON at position 1actually means that it JSON.parsewas applied to what is unacceptable. JSON is a random string or value that is not a string that has been forcibly bound to a string.

Unexpected token o ... , , , , [object ...].

:

Response
  body: ReadableStream
    locked: true
    __proto__: Object
  bodyUsed: true
  ...

Response Response constructor ( Fetch API) ReadableStream .

Fetch polyfill, , res.json() , JSON.parse

this.json = function() {
  return this.text().then(JSON.parse)
}

new ResponseOptions , Response, , .

Angular Response class, Fetch Response, , , . , , Response.

import { Response, ResponseOptions, ... } from '@angular/http';

Typescript, , :

custom.d.ts

declare var Headers: undefined;
declare var Request: undefined;
declare var Response: undefined;
declare var URLSearchParams: undefined;

Http :

TS2532: , undefined.

, API- Fetch Angular.

HttpClient, Http Angular 4.3 , , API- Fetch.

+16

.

, , , .

"".

. ( Stringify , , )

0

, Response:

: import { BaseRequestOptions, Http, ResponseOptions } from '@angular/http';

: import { BaseRequestOptions, Http, Response, ResponseOptions } from '@angular/http';

Response @angular/http, Response API- ECMAScript.

0

SyntaxError: o JSON 1

:

  • , Content-Type JSON API, String o. , , Unexpected token o in JSON at position 1.
  • text/html, , application/json, . , unexpected token o.

JSON, response.json().

0

Source: https://habr.com/ru/post/1016762/


All Articles