Zsolt Makrai Zsolt Makrai - 4 months ago 40
Javascript Question

HTTP post request unit testing in Angular 4

I would like to test an HTTP request in Angular 2, but it is not working.
Here is the error message:

ERROR in .../loginservice.service.spec.ts (45,11): ';' expected.

ERROR in .../loginservice.service.spec.ts (45,12): ')' expected.


and here is the code:
It is a post request, and it working properly.

`
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable()
export class LoginService {

constructor(private http: Http) { }

postLoginDetails(loginDetails): Observable<Comment[]> {
const endpoint = 'http://localhost:8080/api/login';
const bodyString = loginDetails;
const headers = new Headers({ 'Content-Type': 'application/json'});
const options = new RequestOptions({headers: headers});

return this.http.post(endpoint, bodyString, options)
.map((res: Response) => res.json())
.catch((error: any) => Observable.throw(error.json().error || 'server error'));
}
}
`


and here is the test for it:
This is the test for the post request. I used different articles to write it and perhaps that is why it is not working.

`
import { TestBed, inject } from '@angular/core/testing';
import {
HttpModule,
Http,
XHRBackend,
ResponseOptions,
Response,
Headers
} from '@angular/http';
import { MockBackend, MockConnection } from '@angular/http/testing';

import { LoginService } from './loginservice.service';

describe('LoginService', () => {

beforeEach(() => {

TestBed.configureTestingModule({
imports: [HttpModule],
providers: [
{ useValue: 'http://localhost:8080/api/login/' },
LoginService,
{ provide: XHRBackend, useClass: MockBackend },
]
});
});

describe('postLoginDetails()', () => {
it('should return an Observable<Comment[]>', inject([LoginService, XHRBackend], (LoginService, mockBackend) => {
const mockResponse = {
status: 'ok',
token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IlRlc3RBZG1pbiIsImFkbWluIjp0cnVlfQ.nhC1EDI5xLGM4yZL2VMZyvHcbcWiXM2RVS7Y8Pt0Zuk'
};

mockBackend.connections.subscribe((connection) => {
const loginDetails = {
email: 'test@example.com',
password: '1234'
};
LoginService.postLoginDetails(loginDetails).subscribe((userInfo) => {
expect(userInfo.length).toBe(2);
expect(userInfo.status).toEqual('ok');
});

}));
});
});

`

Answer Source

There is mismatch } in while closing mockBackend.connections

   describe('postLoginDetails()', () => {
        it('should return an Observable<Comment[]>', inject([LoginService, XHRBackend], (loginService, mockBackend) => {
            const mockResponse = {
                    status: 'ok',
                    token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IlRlc3RBZG1pbiIsImFkbWluIjp0cnVlfQ.nhC1EDI5xLGM4yZL2VMZyvHcbcWiXM2RVS7Y8Pt0Zuk'
            };

        mockBackend.connections.subscribe((connection) => {
            const loginDetails = {
                email: 'test@example.com',
                password: '1234'
                };
            loginService.postLoginDetails(loginDetails).subscribe((userInfo) => {
                expect(userInfo.length).toBe(2);
                expect(userInfo.status).toEqual('ok');
            });

        }));
    });
});

update:- fixed some syntax error.