M'sieur Toph'
M'sieur Toph'

Reputation: 2676

Testing Service : Difference between MockBackend method and spyOn().and.returnValue() method

These two tests seem to work (at least in my case)

Do exist some specific differences between these two methods ? And how to decide the one I should use (best practices for testing service using Http) ?

1. Using MockBackend method

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. Using spyOn().and.returnValue() method

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

}));

Upvotes: 1

Views: 361

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 208994

Use the MockBackend because there may by other things that you should also probably test, like that the URL is correct, that correct headers are added, etc. All these things can be obtained from the Request from the MockConnection

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

These are things you should test, as having an unexpected URL will cause the request to fail in the app. So you should test it. As well as headers, and whatever else is pertinent to the request.

Upvotes: 2

Related Questions