UnitTest Mock Http response in Angular2 (2.1.0) Service

时间:2016-10-20 13:06:01

标签: unit-testing angular angular2-testing

I am very confused by the different sources online about testing Angular2, mainly due to differences in versions. I am using Angular 2.1.0 final and I don't understand how to mock a simple http response for my service test class below:

import { TestBed, async, inject } from '@angular/core/testing';
import { PersonService } from '../services/person.service';
import { Person} from '../models/Person';
import { MOCK_DATA_PERSON } from '../test/mocks/mock-data-person';

// HTTP mocking imports
import { Http, BaseRequestOptions, Response, HttpModule, ResponseOptions } from '@angular/http';
import { MockBackend, MockConnection } from '@angular/http/testing';


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

        TestBed.compileComponents();
    }));

    it('returns a list of persons', async(inject([MockBackend, PersonService], (backend: MockBackend, service) => {

        backend.connections.subscribe(
            (connection: MockConnection) => {
                connection.mockRespond(new Response(
                    new ResponseOptions({
                        body: JSON.stringify({name: "Bob", surname : "Jones"})
                    })));
            });

        service.getPersons()
            .subscribe(persons=> {
                expect(persons.length).toBeDefined();
                expect(persons.length).toBe(1);
            }).catch(error => console.log(error));
    })));


});

given the getPersons method looks like:

getPersons (): Observable<Person[]> {
    return this.http.get(this.getAllUrl)
      .map(res.json().data)
      .catch(this.handleError);
  }

i am getting the error "Failed: this.http.get(...).map is not a function"

1 个答案:

答案 0 :(得分:2)

Test is good, but the Observable.map operator isn't found. Try to just import it

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