13

Suppose we have this method in a service that return an Observable:

getSearchResults(request: LocationSearchRequest){
      return this.http.get(this.getApiUrl(request))
            .map(res => <LocationSearchResponse> res.json())    
            .catch(this.handleError);    
}

How can I modify this code to return the mocked data ratehr then making an actual GET requesr?

import { MOCKEDDATA } from './mocked-data';

It's not a duplicate question. This has nothing to do with testing, jasmine and angualr2 testing api.

Artur Stary
  • 724
  • 2
  • 13
  • 30
  • 1
    The solution was to use Observable.of(); Why is it marked as duplicate? This has nothing to do with testing, jasmine and angular2 testing api. – Artur Stary Jun 20 '16 at 12:56

4 Answers4

28

Xavi's answer is great and simple, but it didn't work for me - I tweaked it like so:

import { of } from 'rxjs';

And then:

return of(MOCKEDDATA);

Hope this helps someone else too!

Joel Balmer
  • 1,428
  • 2
  • 19
  • 21
15

I had the same topic some time ago. It is also possible to use the method:

Observable.create()

It was solved by the code below (using typescript):

getElementTemplateNames() : Observable<string[]> {
let names : string[] = MockedElementData.getNames();
return Observable.create( observer => {
    observer.next(names);
    observer.complete();
});}

MockedElementData holds the data.

The import statement for Observable is:

import { Observable } from "rxjs/Observable";
b4n4n4
  • 181
  • 2
  • 8
8

You can do:

Observable.of(MOCKEDDATA)

You can also add a delay:

Observable.of(MOCKEDDATA).delay(1000)

Xavi
  • 99
  • 1
  • 6
2

I achieved this issue with the following code.

 this.treeService
          .getData()
          .pipe(takeUntil(this.destroy$))
          .subscribe(
            (fa) => {              
              this.Items = fa.map(f => new TreeviewItem(f));                          
              console.log('this.Items', this.Items);              
            }
          );

Take in consideration that your tree nodes needs to have in all levels. text: "text" value: "value"