Zsolt Makrai
Zsolt Makrai

Reputation: 123

HTTP post request unit testing in Angular 4

THIS TEST IS WORKING NOW!

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: [
                LoginService,
                { provide: XHRBackend, useClass: MockBackend },
            ]
        });
    });

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

            const loginDetails = {
                email: '[email protected]',
                password: '1234'
                };
            MockBackend.connections.subscribe((connection) => {
                connection.mockRespond(new Response(new ResponseOptions({
                    body: JSON.stringify(mockResponse)
                })));
            });
            LoginService.postLoginDetails(loginDetails).subscribe((mockResponse) => {
                expect(mockResponse.status).toEqual('ok');
            });
        }));
    });
});

Upvotes: 3

Views: 4135

Answers (2)

balintd
balintd

Reputation: 93

Nice question. Yes, this is definitely a false positive test...

Upvotes: 0

CharanRoot
CharanRoot

Reputation: 6325

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: '[email protected]',
                password: '1234'
                };
            loginService.postLoginDetails(loginDetails).subscribe((userInfo) => {
                expect(userInfo.length).toBe(2);
                expect(userInfo.status).toEqual('ok');
            });

        }));
    });
});

update:- fixed some syntax error.

Upvotes: 1

Related Questions