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;
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