Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock or override extended class in angular2

Hello every body i have some problems with angular2 unit tests. Can anybody help me?
I have some class like this

export class PostcodeApiService extends ApiService {

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

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);
          });
    });
  }


}

How can do mock of ApiService.post() function?

My spec file look 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 ?
  }));
  
  
  
});

I would be grateful if you could help me with this thing. Thanks for attention!

like image 838
Henry Avatar asked Jan 24 '26 15:01

Henry


1 Answers

Create a mock class:

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

and provide it with

    { provide: PostcodeApiServce, useClass: PostcodeApiServiceMock }

You can find a good example here:

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

like image 131
Markus Avatar answered Jan 27 '26 03:01

Markus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!