3

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"

nuvio
  • 2,555
  • 4
  • 32
  • 58

1 Answers1

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';
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • Ok, you are right, but `map` was imported in the `person.service.ts` so I don't understand why would I have to import it into the `person.service.spec.ts` ... – nuvio Oct 20 '16 at 13:20
  • 1
    I don't either. It happens to me sporadically also :-/ I just import it to make it happy. I'm sure there's an explanation (and resolution), but I just decided to give in. – Paul Samsotha Oct 20 '16 at 13:24