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']);
});
}));
它是有道理的;)Thx。 –