HTTP testing with mockbackends not working

Try the test, but you get this error message:

The expected Object will be some sort of Object, but there was a Response with status: null null for URL: null.

Any idea what's missing here?

login.component.ts:

loginEvent(username, passw) {
      let obj = {
          user: username,
          pass: passw
      };

  if (this.validation(obj)) { 
      this.httpService.loginPostToServer(obj).subscribe(
          (response) => this.saveTokenToLocalstorage(response),
          (error) => console.log(error)
      );
    }
  };

      

http.service.ts:

loginPostToServer(data) {
    return this.http.post(this.url + 'login', data);
}  

      

Test:

import { async, TestBed, inject } from '@angular/core/testing';
import { HttpModule, Http, ResponseOptions, Response, BaseRequestOptions } from '@angular/http';
import { MockBackend } from '@angular/http/testing';
import { HttpService } from './http.service';

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

it('should be created', inject([HttpService], (service: HttpService) => {
    expect(service).toBeTruthy();
}));

it('should construct', async(inject(
    [HttpService, MockBackend], (service, mockBackend) => {
    expect(service).toBeDefined();
})));

describe('loginPostToServer', () => {
    const mockResponse = {
    success: true,
    token: "sample token",
    user: "john"
    };

    const fakeUser = {
    user: "john",
    pass: "1234"
    };

    it('should parse response', async(inject(
    [HttpService, MockBackend], (service, mockBackend) => {

    mockBackend.connections.subscribe(conn => {
        conn.mockRespond(new Response(new ResponseOptions({ body: JSON.stringify(mockResponse) })));
    });

    const result = service.loginPostToServer(fakeUser);

    result.subscribe(res => {
        expect(res).toEqual({
        success: true,
        token: "sample token",
        user: "john"
        });
    });
    })));
});
});

      

+3


source to share


1 answer


The problem is that the response object returned from the HTTP request contains the data you want, but is not needed by itself.

To access the data inside the request (i.e. the body of the request), you need to call the .json () method:



  if (this.validation(obj)) { 
      this.httpService.loginPostToServer(obj).subscribe(
          (response) => this.saveTokenToLocalstorage(response.json()), // .json() added here
          (error) => console.log(error)
      );
    }
  };

      

+1


source







All Articles