2017-04-12 22 views
1

這兩項測試似乎工作(至少在我的情況)測試服務:MockBackend方法和spyOn之間的差異()and.returnValue()方法

確實存在,這兩種方法之間的一些具體區別在哪裏? 以及如何決定我應該使用的一個(使用Http測試服務的最佳實踐)?

1.使用MockBackend方法

beforeEach(() => { 
    TestBed.configureTestingModule({ 
    providers: [ 
     MyService, 
     MockBackend, 
     BaseRequestOptions, 
     { 
      provide: Http, 
      deps: [MockBackend, BaseRequestOptions], 
      useFactory: (backend: XHRBackend, defaultOptions: BaseRequestOptions) => new Http(backend, defaultOptions) 
     } 
    ], 
    imports: [HttpModule] 
    }).compileComponents(); 
}); 

it('#getResources should get an items list', 
    async(inject([MyService], (service: MyService) => { 

    TestBed.get(MockBackend).connections.subscribe(
     (connection: MockConnection) => connection.mockRespond(new Response(
      new ResponseOptions({ 
      body: { 
       items: ['foo','bar'] 
      } 
      }) 
     )) 
    ); 

    service.getResources('/foobar').subscribe(items => { 
     expect(items).toEqual(['foo','bar']); 
    }); 

    })) 
); 

2.使用spyOn()。and.returnValue()方法

let backend: XHRBackend; 
let defaultOptions: BaseRequestOptions; 
let http = new Http(backend, defaultOptions); 

it('#getResources should get an items list', async(() => { 

    const spy = spyOn(http, 'get') 
       .and.returnValue(
       Observable.of(new Response(new ResponseOptions({ 
        body: {items: ['foo','bar']} 
       })) 
      )); 

    let service = new MyService(http); 
    service.getResources('/foobar').subscribe(items => { 
    expect(items).toEqual(['foo','bar']); 
    }); 

})); 

回答

2

使用MockBackend因爲有通過其他的東西可以由你也應該測試一下,比如URL是否正確,是否添加了正確的頭文件等等。所有這些東西都可以從得到MockConnection

TestBed.get(MockBackend).connections 
.subscribe((connection: MockConnection) => { 
    const request = connection.request; 
    expect(request.url).toBe(...) 
}) 
); 

這些都是你應該測試作爲具有意想不到的URL會導致請求的應用程序失敗。所以你應該測試它。以及標題,以及與請求相關的其他內容。

+0

它是有道理的;)Thx。 –

相關問題