【问题标题】:Mock or override extended class in angular2模拟或覆盖angular2中的扩展类
【发布时间】:2018-01-04 14:28:48
【问题描述】:

大家好,我在 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() 函数?

我的规范文件是这样的

describe('PostcodeApiService', () => {


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

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

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

【问题讨论】:

    标签: angular unit-testing typescript


    【解决方案1】:

    创建一个模拟类:

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

    并提供给它

        { provide: PostcodeApiServce, useClass: PostcodeApiServiceMock }
    

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

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

    【讨论】:

    • 不知何故这对我和afaik不起作用,您只能以这种方式覆盖注射剂(在示例中HttpAuthService),而不是扩展类:(有没有办法完全交换服务的超类(又名原型)进行测试?
    猜你喜欢
    • 2018-01-05
    • 2017-10-21
    • 1970-01-01
    • 1970-01-01
    • 2017-06-28
    • 1970-01-01
    • 2011-10-15
    • 2018-07-21
    • 2016-09-30
    相关资源
    最近更新 更多