Mock or override extended class in angular2

Hi everyone, I have some problems with angular2 unit tests. Can anyone help me?
I have a class like this

export class PostcodeApiService extends ApiService {

  constructor(Http: Http, auth: AuthService) {
    super(Http, auth);
  }
  
  getPostcodes(filterObject) {
    return super.post('postcodes/filter', filterObject );
  }
}
      

Run codeHide result


export class ApiService {


  constructor(private http: Http) {
  }

  post(url, payload: any) {
    return new Observable((observer) => {
        this.http.post(`someUrl/${url}`, payload)
          .map((res: Response) => res.json())
          .catch((error: any) => {
            return Observable.throw(error || `Server error ${url}`);
          })
          .subscribe((data) => {
            observer.next(data);
          });
    });
  }


}
      

Run codeHide result


How can the ApiService.post () function be used?

My spec file looks like this

describe('PostcodeApiService', () => {


  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        PostcodeApiService,
        Http,
        ConnectionBackend,
        AuthService,
        UserService
      ],
      imports: [
        HttpModule
      ]
    });
  });

  it('should ...', inject([PostcodeApiService], (service: PostcodeApiService) => {
    // How ovveride post method ?
  }));
  
  
  
});
      

Run codeHide result


I would be grateful if you can help me with this. Thanks for your attention!

+3


source to share


1 answer


Create a mock class:

    class PostcodeApiServiceMock extends PostcodeApiService {
      post(url, payload: any) {
        // do something
      }
    }

      

and provide him



    { provide: PostcodeApiServce, useClass: PostcodeApiServiceMock }

      

You can find a good example here:

https://angular.io/guide/testing#test-a-routed-component

+2


source







All Articles