在angular2中模拟或覆盖扩展类

时间:2017-07-28 13:30:57

标签: angular unit-testing typescript

大家好我对angular2单元测试有些问题。有谁能够帮我?我有这样的课程



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


}




如何模拟ApiService.post()函数?

我的spec文件看起来像这样



describe('PostcodeApiService', () => {


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

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




如果你能帮我解决这个问题,我将不胜感激。 感谢您的关注!

1 个答案:

答案 0 :(得分:1)

创建一个模拟类:

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

并提供

    { provide: PostcodeApiServce, useClass: PostcodeApiServiceMock }

你可以在这里找到一个很好的例子:

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